Reputation: 2633
I have an object:
let object1 = { a: 'one', b: 'two', c: 'three' };
I'm trying to set object1.a to be a key for object2:
object2 = { key: 'something' };
I tried to make key as:
[object1].a
object1.a
object1[a]
I remember I have to use bracket notation but can't figure out how to do this?
The reason I want to do this is because I'm going to change the values of object1 depending on props so I can just have a single component that changes key based on prop received.
Upvotes: 4
Views: 9632
Reputation: 1075765
If object2
already exists, you just use brackets notation:
object2[object1.a] = 'something';
Now, object2
has a property called one
that has the value 'something'
.
If you're creating object2, in ES5 you have to create the object separately first, and then add the property:
var object2 = {};
object2[object1.a] = 'something';
In ES2015 ("ES6"), you can use a computed property name in the initializer (note the []
):
// ES2015 only!
let object2 = {
[object1.a]: 'something'
};
Just as with bracket notation when you're doing assignment, you can have any expression within those brackets in the initializer.
Note that this does not create ongoing link between the objects. It purely evaluates the value of object1.a
at the moment the initializer is processed, and uses the resulting value as the name of the new property on the new object.
Upvotes: 12