Skip to content
Advertisement

Create object from array

I want to create an object from a list inside an array. I have an array which is dynamic and supposed to look like this:

var dynamicArray = ["2007", "2008", "2009", "2010"];

And I want to make an object like this with some JavaScript ES6:

JavaScript

Don’t worry about the inner objects. I just want to create a structure like this:

JavaScript

Please help, thanks.

Advertisement

Answer

Simply

JavaScript

or if you prefer “functional” style:

JavaScript

using the modern object spread operator:

JavaScript

Example:

JavaScript

Here is how it works:

reduce is initialized with an empty object (empty {} at the end), therefore first iteration variables are acc = {} cur = { id: 10, color: "red" }. Function returns an object – this is why function body is wrapped in parentheses => ({ ... }). Spread operator doesn’t do anything on the first iteration, so red: 10 is set as first item.

On the second iteration variables are acc = { red: 10 } cur = { id: 20, color: "blue" }. Here the spread operator expands acc and the function returns { red: 10, blue: 20 }.

Third iteration acc = { red: 10, blue: 20 } cur = { id: 30, color: "green" }, so when acc is spread inside the object, our function returns the final value.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement