2

Is there a better title for this?

Okay, is something like this legal?

var myobj = {
    key1: "val1",
    key2: this.key1
};

I haven't tried it, but I'm looking for a way to have identical values for separate keys in an object, preferably in a concise way.

2 Answers 2

2

Your code is legal but doesn't do what you mean. When evaluating the key:... part this is not bound to the yet-non-existent object, but to the context where myobj is being built. You have to store the value in a variable and then using the variable... like:

var kv = "val1";
var myobj = {
    key1: kv,
    key2: kv
};

note that here you're not creating a closure if this is your fear. That only happens for function expressions

1

try:

var myobj = {};
myobj['key2'] = (myobj['key1'] = 'val1');

Since in javascript, value assignment also returns the value as well, so you can be somewhat concise.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.