0

Pretty simple question. I have some assumptions why this doesn't work, but would like a more scholarly explanation.

This works:

newArray = oldArray.map(function(obj){
    return {'key': 'value'};
});

While this doesn't:

newArray = oldArray.map(function(obj){
    return {obj.key: obj.value};
});
Half_Duplex
  • 5,102
  • 5
  • 42
  • 58
  • Well, my first thought is that without some additional syntax, how would JavaScript know whether you mean for the property to be named "obj.key" or be named from the value contained within obj.key? – adam0101 May 23 '16 at 20:14
  • I couldn't find a similar question with a good answer. Maybe I just don't know the best search key words. Any suggestions @Quentin? – Half_Duplex May 23 '16 at 20:59
  • @adam0101 If that were the case I'd immediately see those values in the newly created array. – Half_Duplex May 23 '16 at 21:03
  • @Half_Duplex — Err… the link in the big yellow box at the top of the question? – Quentin May 23 '16 at 21:05
  • @Half_Duplex, of course you wouldn't see those values as it's invalid syntax. I wasn't saying that's how it works. I was saying that what you want _can't_ work because of that. At least, not without additional syntax as is available in ECMA6. That's because `{a: 1}` and `{'a': 1}` are both valid means of declaring an object literal. – adam0101 May 23 '16 at 21:58
  • @Quentin Thanks for adding a link to the correct answer, I don't believe it was there when I commented the first time and obviously my JS vernacular is lacking. – Half_Duplex May 24 '16 at 13:36
  • @Half_Duplex — It was added automatically by the system when the question was closed. – Quentin May 24 '16 at 13:37

2 Answers2

3

With ECMA6 syntax you can do:

newArray = oldArray.map(obj => {
    return {[obj.key]: obj.value};
});

If you want to support older browsers, you will need to make a temporary object:

newArray = oldArray.map(function(obj) {
    var newObj = {};
    newObj[obj.key] = obj.value;
    return newObj;
});
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
2

You would need to do it via

newArray = oldArray.map(function(obj){
    var foo = {};
    foo[obj.key] = obj.value;
    return foo;
});

There is a way to do what you want in ES6 with square brackets.

epascarello
  • 204,599
  • 20
  • 195
  • 236