Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group object as 2d array by key

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?

like image 693
Ekoar Avatar asked Jun 11 '26 10:06

Ekoar


1 Answers

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);
like image 167
Eddie Avatar answered Jun 13 '26 22:06

Eddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!