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

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

Something like the following:

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


But this leads to:

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

but not:

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

+4
source share
1 answer

You can use the computed properties :

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);
Run code
+18
source

Source: https://habr.com/ru/post/1664620/


All Articles