4

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.

asked Jun 22, 2016 at 14:13
9
  • 2
    stackoverflow.com/questions/4244896/… Commented Jun 22, 2016 at 14:14
  • 1
    object1.a = object2? Commented Jun 22, 2016 at 14:14
  • object1['a'] = ""; you can use it like this Commented Jun 22, 2016 at 14:15
  • object2['a'] = object1['a'] Commented Jun 22, 2016 at 14:16
  • object2[object1.a] = something; Commented Jun 22, 2016 at 14:16

1 Answer 1

12

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.

answered Jun 22, 2016 at 14:18
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works :) I didn't know you can use dot notation inside bracket notation.
@cocacrave - You can put any expression inside the square brackets, e.g., it's quite legal to say something like object2[condition ? "test" : callFunc() + object1.a + "another string"].

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.