Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object key as variable

Tags:

javascript

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.

like image 903
cocacrave Avatar asked Oct 18 '25 03:10

cocacrave


1 Answers

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.

like image 62
T.J. Crowder Avatar answered Oct 20 '25 18:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!