展平嵌套数组

时间:2020-09-23 09:53:01

标签: javascript arrays json underscore.js

我正在使用Underscore,但有一个对象

[{
  name: "aaa",
  date: "2020",
  time: [20, 10, 30],
  meal: ["before", "after", "before"],
  amount: [1, 2, 3]
}, {
  name: "bbb",
  date: "2021",
  time: [200, 100, 300],
  meal: ["before", "after", "before"],
  amount: [10, 20, 30]
}]

我想用时间/膳食/数量重复函数中的每个项目,像这样:

[{
  name: "aaa",
  date: "2020",
  time: 20,
  meal: "before",
  amount: 1
},{
  name: "aaa",
  date: "2020",
  time: 10,
  meal: "after",
  amount: 2
},{
  name: "aaa",
  date: "2020",
  time: 30,
  meal: "before",
  amount: 3
}, {
  name: "bbb",
  date: "2021",
  time: 200,
  meal: "before",
  amount: 10
},{
  name: "bbb",
  date: "2021",
  time: 100,
  meal: "after",
  amount: 20
},{
  name: "bbb",
  date: "2021",
  time: 300,
  meal: "before",
  amount: 30
}]

然后我要按时间和用餐分组。 我尝试了很多事情,但无法得到结果。

2 个答案:

答案 0 :(得分:0)

如果timemealamount的长度始终相同,则可以使用flatMap创建具有相同属性的新对象并将其平整为新数组。

const data=[{name:"aaa",date:"2020",time:[20,10,30],meal:["before","after","before"],amount:[1,2,3]},{name:"bbb",date:"2021",time:[200,100,300],meal:["before","after","before"],amount:[10,20,30]}];

const combos = data.flatMap(({time, meal, amount, ...rest}) => {
  return time.map((num, index) => ({
    ...rest,
    time: num,
    meal: meal[index],
    amount: amount[index],
  }));
});

console.log(combos);
.as-console-wrapper{min-height:100%;}

答案 1 :(得分:0)

如果说您的数组位于变量x中,则可以简单地执行操作,而无需使用下划线:

var y = [];
x.forEach(z => {
  z.meal.forEach((val, index) => {
    y.push({
      name: z.name,
      date: z.date,
      time: z.time[index],
      meal: val,
      amount: z.amount[index]
    });
  });
});

y将包含您的新数组。 如果您随后想按某个字段分组或执行其他聚合,并且知道SQL,那么使用alasql是一种有趣的方法。包括/要求它,然后您就可以这样做:

alasql('SELECT name, date, time, meal, SUM(amount) FROM ? GROUP BY time, meal',[y]);