I am trying to change the data structure of an array of objects in JS. I have an array of objects that contain the same keys that I would like to merge to one for example route
. And then would like to add query
and time
in a new array. Example below:
How do I change this data structure:
const array = [
{
query: "query1",
route: "home",
time: 1234
},
{
query: "query2",
route: "dashboard",
time: 4324
},
{
query: "query3",
route: "home",
time: 1200
},
{
query: "query4",
route: "admin",
time: 3333
},
{
query: "query5",
route: "admin",
time: 5435
},
]
to become this:
const array = [
{
route: "home",
calls: [
{
query: "query1",
time: 1234
},
{
query: "query3",
time: 1200
},
]
},
{
route: "dashboard",
calls: [
{
query: "query2",
time: 4324
},
]
},
{
route: "admin",
calls: [
{
query: "query4",
time: 3333
},
{
query: "query5",
time: 5435
},
]
}
]
Thanks in advance
CodePudding user response:
You can use reduce
method and group the array
with key
equal to route
property, and then use Object.values
to get the values of the object.
const array = [
{
query: "query1",
route: "home",
time: 1234
},
{
query: "query2",
route: "dashboard",
time: 4324
},
{
query: "query3",
route: "home",
time: 1200
},
{
query: "query4",
route: "admin",
time: 3333
},
{
query: "query5",
route: "admin",
time: 5435
},
]
const result = Object.values(array.reduce((acc, item) => {
acc[item.route] ? acc[item.route].cells.push({query: item.query, time: item.time}) : (acc[item.route] = {route: item.route, cells: [{query: item.query, time: item.time}]})
return acc
}, {}))
console.log(result)
CodePudding user response:
You could use a Map
to key the target objects by route, initially with empty call
arrays. Then populate those call
arrays and finally extract the values from the Map into the result array:
const array = [{query: "query1",route: "home",time: 1234},{query: "query2",route: "dashboard",time: 4324},{query: "query3",route: "home",time: 1200},{query: "query4",route: "admin",time: 3333},{query: "query5",route: "admin",time: 5435},]
const map = new Map(array.map(({route}) => [route, { route, calls: [] }]));
for (const {route, ...rest} of array) map.get(route).calls.push(rest);
const result = [...map.values()];
console.log(result);