arrays - Use the value of a string variable as the 'index' of an existing object in Javascript -


I am using JavaScript.

"Name": "mike", "no": "b456"}, "three": {"name": "andy", "no": "c789"},};

I have another object newitem which I want to insert

  var newIndex = "four"; Var newItem = {"name": "leo", "no": "D987"}; How to insert  

as newItem in myobj as the 'index' in the form of 'newIndex' Can i

By the way, newIndex is not generated by me, so I just have to go to myobj.four = newItem; myobj.newIndex = newItem does not work because it uses the word 'New Index' as an indicator instead of its value.

Any insights?

Use the bracket notation property accelerator:

  myobj [newIndex ] = NewItem;  

This is also useful when you want to define an asset whose name is not a valid identifier, for example:

  obj ["1foo"] = "Bar"; // `obj.1for` will be a syntax array oz [" ab "] =" bar "; // `obj.ab` will be the cause of a syntax error  

Note that you can also use expressions with this property assessor, such as:

  obj [someFunc ()] = "foo";  

This will evaluate the expression between the bracket, and it will convert the result to string, because javascript does not contain true hash tables, the property name should be type String

More info:


Comments