Adding a key from a variable string (es6) when using spread syntax

JasoonS picture JasoonS · Dec 22, 2016 · Viewed 7.8k times · Source

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"}, ... }

Answer

Michał Perłakowski picture Michał Perłakowski · Dec 22, 2016

You can use computed properties:

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);