I want to create object from list of array. I have an array which is dynamic which suppose to be look like this:
var dynamicArray = ["2007", "2008", "2009", "2010"];
and with some javascript es6 I want to make an object like this:
const obj = {
2007: {
x: width / 5,
y: height / 2
},
2008: {
x: (2 / 5) * width,
y: height / 2
},
2009: {
x: (3 / 5) * width,
y: height / 2
},
2010: {
x: (4 / 5) * width,
y: height / 2
}
}
don't worry about inner objects but just wanted to a make structure like this:
obj = {
2007: ...,
2008: ...,
...
}
Please help, Thanks.
Simply
or if you prefer "functional" style:
using the modern object spread operator:
Example:
Output:
Here is how it works:
reduce
is initialized with an empty object (empty{}
at the end), therefore first iteration variables areacc = {}
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, sored: 10
is set as first item.On the second iteration variables are
acc = { red: 10 }
cur = { id: 20, color: "blue" }
. Here the spread operator expandsacc
and the function returns{ red: 10, blue: 20 }
.Third iteration
acc = { red: 10, blue: 20 }
cur = { id: 30, color: "green" }
, so whenacc
is spread inside the object, our function returns the final value.you can use:
in js with es6 reduce function for array I do it like this