0

I want to provide a value for object property but it is coming from another object. This is situation like this:

 c.query('SELECT `' + field + '` FROM `table` WHERE `' + field + '` = :' + field, { field: value }) .on('result', function(res) { res.on('row', function(row) { callback(inspect(row)); }); }); 

i want to automate it in the way that i send object {field: 'someField', value: 'someValue'} and i use reference to set property of object in second line of the code above.

I came up with this code:

 var a = { field: 'email', value: '[email protected]' }; var b = { [a.field]: a.value }; console.log(b); 

it does work in here: jsFiddle, but in actual node.js server script it return error unexpected token "[" so its like i cannot set object property from another object property reference. Anyone has some idea?

2
  • In your real world situation has 'a' been defined and values set by the time it's accessed in 'b'? Commented Jul 30, 2015 at 22:35
  • If you introduce a babel to your node environment, your code will work. Dynamic property assignment to object literals is part of the ES6 spec, which is has very limited support, but works just fine if you transpile your code. Commented Jul 30, 2015 at 22:37

1 Answer 1

2

b = {}; b[a.field] = a.value;

is the closest to your representation that will work across JS versions I suspect.

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

4 Comments

this is what i offered in jsfiddle link, it doesnt work in real environment
@patrickmevia. That is not the same thing you have in your fiddle. This answer separated the initialization of an empty object, then added the property name using bracket access notation. You are trying to do it in one shot. That's not supported until the Harmony version of ECMAScript. See wiki.ecmascript.org/…
yeah that worked, thx
So, the other solution would be to jump from node to io.js.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.