17

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
  • 795,719
  • 175
  • 1,089
  • 1,143
JasoonS
  • 1,432
  • 3
  • 13
  • 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

58

You can use computed properties:

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177