I have an array of objects. These objects have a property called time. I want to group these objects to the same array if their time are same.
{ "00:00" :
[{"id":1, time: "00:05",
{"id":1, time: "00:15",
{"id":1, time: "00:20",
{"id":2, time: "00:05",
{"id":3, time: "00:05",
{"id":4, time: "00:35 }]
}
I want to format the above data as:
{ "00:00" :[
[{"id":1, time: "00:05"}, {"id":2, time: "00:05"}, {"id":3, time: "00:05"}],
[{"id":1, time: "00:15" }],
[{"id":1, time: "00:20" }],
[{"id":4, time: "00:35" }]]
}
Any advice on how can I accomplish this?
You can use reduce to summarize your object and use Object.values to convert the object into array
let obj={"00:00" :[{"id":1,time:"00:05"},{"id":1,time:"00:15"},{"id":1,time:"00:20"},{"id":2,time:"00:05"},{"id":3,time:"00:05"},{"id":4,time:"00:35"}],"02:00" :[{"id":1,time:"00:05"},{"id":1,time:"00:15"},{"id":1,time:"00:20"},{"id":2,time:"00:05"},{"id":3,time:"00:05"},{"id":4,time:"00:35"}]}
var result = Object.entries(obj).reduce((c, v) => {
c[v[0]] = Object.values(v[1].reduce((a, o) => {
a[o.time] = a[o.time] || [];
a[o.time].push(o);
return a;
}, {}));
return c;
}, {});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With