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

11.4k views Asked by At

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

1

There are 1 answers

0
Michał Perłakowski On BEST ANSWER

You can use computed properties:

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