14

I would like to know if there is a clean way to set the value of a key from a string variable when using spread syntax in es6?

Something like the following:

let keyVar = 'newKey'
let newObject = {keyVar:{some:'json'},...oldObject}


But this leads to:

{"keyVar":{"some":"json"}, ... }

rather than:

{"newKey":{"some":"json"}, ... }

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
JasoonS
  • 1,392
  • 2
  • 12
  • 26
  • 1
    FYI, "spread properties" are not part of ES6. They are currently a proposal, i.e. an experimental feature. But it doesn't change how to set the property anyway. It also has nothing to do with JSON. – Felix Kling Dec 22 '16 at 22:58

1 Answers1

49

You can use computed properties:

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);
Michał Perłakowski
  • 80,501
  • 25
  • 149
  • 167