通过键将对象分组为2d数组 [英] group object as 2d array by key

查看:66
本文介绍了通过键将对象分组为2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组.这些对象具有称为time的属性.如果它们的时间相同,我想将这些对象分组到同一数组.

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?

推荐答案

使用.reduce将所有匹配的对象放入按时间索引的对象内部的数组,然后从该对象中提取值:

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

您还可以扩展它以将其应用于input数组的多个属性:

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

这篇关于通过键将对象分组为2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆