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
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)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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?
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);
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?
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
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}
];
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)