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"}, ... }
JavaScript ES6— The Spread Syntax (…) The spread syntax is simply three dots: ... It allows an iterable to expand in places where 0+ arguments are expected. Definitions are tough without context. Lets explore some different use cases to help understand what this means. Take a look at the code below.
Spread syntax (...) Spread syntax ( ...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop: var thetop = 'top'; var config = { [thetop] : 10 }; // config.top = 10 <something>.stop ().animate (config, 10); The square bracket syntax has been introduced with ES6.
Rest syntax (parameters) Rest syntax looks exactly like spread syntax but is used for destructuring arrays and objects. In a way, rest syntax is the opposite of spread syntax: spread 'expands' an array into its elements, while rest collects multiple elements and 'condenses' them into a single element.
You can use computed properties:
const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With