I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object; var a = 'string1'; var b = 'string2'; myObj.a = b; alert(myObj.string1); //Returns 'undefined' alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
assign() The Object. assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Note browser support is currently negligible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With