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: 'john.doe@gmail.com'
    };

    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?

Mevia
  • 1,517
  • 1
  • 16
  • 51
  • In your real world situation has 'a' been defined and values set by the time it's accessed in 'b'? – bluesman Jul 30 '15 at 22:35
  • If you introduce a [babel](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals) 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. – bioball Jul 30 '15 at 22:37

1 Answers1

2

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

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

Paul Marrington
  • 557
  • 2
  • 7
  • this is what i offered in jsfiddle link, it doesnt work in real environment – Mevia Jul 30 '15 at 22:29
  • 1
    @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 http://wiki.ecmascript.org/doku.php?id=harmony:object_literals#object_literal_computed_property_keys – Ruan Mendes Jul 30 '15 at 22:39
  • yeah that worked, thx – Mevia Jul 30 '15 at 23:05
  • So, the other solution would be to jump from node to io.js. – Paul Marrington Jul 31 '15 at 00:28