Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 502
JasoonS Avatar asked Dec 22 '16 22:12

JasoonS


People also ask

What is spread syntax in JavaScript ES6?

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.

What is spread syntax in Python?

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.

How to get the value of the variable thetop in ES6?

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.

What is the difference between rest and spread syntax?

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.


1 Answers

You can use computed properties:

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);
like image 152
Michał Perłakowski Avatar answered Sep 25 '22 01:09

Michał Perłakowski