1

I am aware I can use another object's property as a key to declare a property of the object, like so:

var object1 = {
    myAttr: 'myName'
};
var object2 = {};
var object2[object1.myAttr] = 'myValue';

Then we have object2.myName == 'myValue'.

How would I go about doing that directly in the object's declaration? Something like that:

var object1 = {
    myAttr: 'myName'
};
var object2 = {
    object1.myattr: 'myValue'
};

But that actually works.

2
  • 1
    You wouldn't, it's that simple ! Commented Jun 3, 2014 at 12:45
  • Bummer. Alright then, thank you! Commented Jun 3, 2014 at 12:46

2 Answers 2

2

You could change your code a bit and do this:

var object1 = {
     myAttr: 'myName'
};

var object2 = new function(){
    this[object1.myAttr] = 'myValue'
}();

You can evolve this and pass object1 as an attribute to the object2 function and things go on...

Sign up to request clarification or add additional context in comments.

Comments

-1

You can do using eval function of javascript

var object1 = {   myAttr: 'myName' };
eval("var object2 = { "+object1.myAttr+": 'myValue' }");
console.log(object2.myName);

Comments

Your Answer

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.