I am using JavaScript.
I have
var myobj = {
"one": {
"name": "paul",
"no" : "A123"
},
"two": {
"name": "mike",
"no" : "B456"
},
"three": {
"name": "andy",
"no" : "C789"
},
};
I have another object newitem that I want to insert
var newIndex = "four";
var newItem = {
"name": "leo",
"no" : "D987"
};
How do I insert newItem into myobj using newIndex as the ‘index’?
By the way, newIndex is not generated by me so I cannot just say myobj.four = newItem; myobj.newIndex = newItem doesn’t work since it uses the word ‘newIndex’ as the index instead of its value.
Any insights?
Use the bracket notation property accessor:
It is also useful when you want to define a property whose name is not a valid Identifier, e.g.:
Note that you can even use an expression with this property accessor, e.g.:
It will evaluate the expression between the brackets, and it will convert the result to string, because JavaScript doesn’t have true hash tables, property names must be of type String.
More info: