展平嵌套数组

Flatten nested array

我正在使用 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]
}]

我想用 time/meal/amount 重复函数中的每个项目,如下所示:

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

那我要按时间和餐点分组。 我尝试了很多东西,但我无法得到我想要的结果

如果 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%;}

如果假设你的数组在变量 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。 Include/require 它然后你可以这样做:

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