DEV Community

loading...

Discussion on: How to convert an array into an object in javascript

Collapse
nicolege profile image
nicole-ge

I have another example to wotk with your Code, but I didn't reach it.

My Array:

[
{"name":"Product 1","series":{"name":"Area 1","value":3}},
{"name":"Product 2","series":{"name":"Area 2","value":3}},
{"name":"Product 1","series":{"name":"Area 2","value":1}},
]

Need to convert it to an object like this:

[ {"name": "Product 1",
"series":[{"name":"Area 1","value":3},{"name":"Area 2","value":1}] },
{"name":"Product 2",
"series":[{"name":"Area 2","value":3}] }
];

It would be nice if you could give my any advice how to reach this by adopting your Code?

Collapse
fetishlace profile image
fetishlace

I would do something like this below to get the result (not nice or fast but should do the job :D):

const arr = [
{"name":"Product 1","series":{"name":"Area 1","value":3}},
{"name":"Product 2","series":{"name":"Area 2","value":3}},
{"name":"Product 1","series":{"name":"Area 2","value":1}},
];

const result = [... new Set(arr.map(x=>x.name))].map(x=>({"name":x,"series":[]}));

arr.forEach(x=>result.find(y=>y.name===x.name).series.push(x.series));

JSON.stringify(result,null,3);

Collapse
nicolege profile image
nicole-ge

Thank you this works very good.

I have one question:
what does arr.forEach(x=>result.find(y=>y.name===x.name).series.push(x.series));

I don't understand this function. I left it out and works. What does it?

Thread Thread
fetishlace profile image
fetishlace

It cannot work without it, it makes no sense. I've just generated array with unique names and empty series array at first (result), this one is pushing all the series objects data into these empty series arrays in result array.

It's just going through original array (arr) to pick series object and push it in result series array - names properties has to match hence y.name===x.name

Thread Thread
nicolege profile image
nicole-ge

to understand the code a bit better, how I have to adjust it to get the following result:

[
{"name":"Area 1","value":3},
{"name":"Area 2","value":3},
{"name":"Area 2","value":1}
];

Thread Thread
fetishlace profile image
fetishlace

From that?
let arr = [
{"name":"Product 1","series":{"name":"Area 1","value":3}},
{"name":"Product 2","series":{"name":"Area 2","value":3}},
{"name":"Product 1","series":{"name":"Area 2","value":1}},
]
U can just remap it
arr.map(x=>x.series)