Use reduce
for object creation
reduce
takes a function as an argument and this function can take several arguments (at least 2), first is called an accumulator
, it contains all sum of all previous calls of this function and the second argument is current
, it contains a current value, in this case current object which we want to transform. As you can see, there is a {}
in the end of reduce
and this is initialValue
which means that at first run of that function which is inside reduce
, accumulator
will be this value, so {}
(empty object)
var arr = [
{
name: "test",
options: [
{id: "1", value: ""},
{id: "2", value: ""},
{id: "3", value: ""},
{id: "4", value: ""}
]
},
{
name: "test2",
options: [
{id: "12", value: ""},
{id: "23", value: ""},
{id: "34", value: ""},
{id: "45", value: ""}
]
}
]
var obj = arr.reduce((obj1, { name, options }) => ({...obj1, [name]: options}), {})
console.log(obj)
9
solved Change array of objects with array inside, to one object [closed]