按对象将对象分组为2d数组

时间:2018-04-28 04:08:12

标签: javascript arrays node.js

我有一个对象数组。这些对象具有名为std::string s; std::cin >> s; return s; 的属性。如果时间相同,我想将这些对象分组到同一个数组中。

time

我想将上述数据格式化为:

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

关于如何实现这一目标的任何建议?

3 个答案:

答案 0 :(得分:3)

你可以尝试使用Array的reduce(),如下所示:

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

答案 1 :(得分:3)

您可以使用reduce汇总您的对象,并使用Object.values将对象转换为数组

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

答案 2 :(得分:2)

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

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数组的多个属性:

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