I have a JSON data that looks like the following:
const data = [{name:"a",version:1}, {name:"a",version:2}, {name:"b",version:3}, {name:"c",version:4}, {name:"c",version:5}]
I need to display the above data in the following format:
Would appreciate any ideas or suggestions on how can I approach this problem. I was thinking of creating a table but would like to know if anyone has a more elegant solution.
CodePudding user response:
A simple way to solve this is using reduce function to build the result that you're looking for, and add just the value of the version concatenated with text "V" and then push it in. Here's a working solution:
const groupBy = (objectArray, property) => {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
const curGroup = acc[key] ?? [];
return { ...acc, [key]: [...curGroup, `V${obj.version}`] };
}, {});
}
const data = [{name:"a",version:1},{name:"a",version:2},{name:"b",version:3},{name:"c",version:4},{name:"c",version:5}]
console.log(groupBy(data, "name"));