Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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);

Solution 2:

You can try with Array's reduce() like the following way:

var 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" }]
}

var res = obj['00:00'].reduce(function(a, c){
  a[c.time] = a[c.time] || [];
  a[c.time].push(c);
  return a;
}, {});

console.log(res);
.as-console-wrapper { top: 0; }

Solution 3:

Use .reduce to put all matching objects into an array inside an object indexed by the time, and then extract the values from the object:

const input = { "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" }]
};
const outputObj = input['00:00'].reduce((accum, { id, time }) => {
  if (!accum[time]) accum[time] = [];
  accum[time].push({ id, time });
  return accum;
}, {});
const outputArr = Object.values(outputObj);
console.log(outputArr);

You can also extend it to apply to multiple properties of the input array:

const input = { "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" }],
    "01:00" :
   [{"id":1, time: "01:05"},
    {"id":1, time: "01:15"},
    {"id":1, time: "01:20"},
    {"id":2, time: "01:05"},
    {"id":3, time: "01:05"},
    {"id":4, time: "01:35" }],
};
function transformInputArrToGroupedArr(inputArr) {
  const outputObj = inputArr.reduce((accum, { id, time }) => {
    if (!accum[time]) accum[time] = [];
    accum[time].push({ id, time });
    return accum;
  }, {});
  return Object.values(outputObj);
}
const transformedInput = Object.entries(input).reduce((accum, [ key, arr ]) => {
  accum[key] = transformInputArrToGroupedArr(arr);
  return accum;
}, {});
console.log(transformedInput);

Post a Comment for "Group Object As 2d Array By Key"