使用 JavaScript 中的 "reduce" 从另一个数组创建新数组

create new array from another array using "reduce" in JavaScript

我有一个 array/list 比如:

var mydata = [
  {"endTime": "123",
  "startTime": "2323",
  "lob" : ["a", "b", "c"]
  },
  {
  "endTime": "454",
  "startTime": "3232",
  "lob" : ["a", "b"]
  },
  {
  "endTime": "4545",
  "startTime": "2322",
  "lob" : ["c"]
  }
]

我想通过这个数组映射并以每个 "lob" 和 [startTime, endTime] 添加到列表的方式创建另一个列表,如下所示:

[
{"item": "a" , timeRange: [123, 2323] },
{"item": "b" , timeRange: [123, 2323] },
{"item": "c" , timeRange: [123, 2323] },
{"item": "a" , timeRange: [454, 3232] },
{"item": "b" , timeRange: [454, 3232] },
{"item": "c" , timeRange: [4545, 2322] },
]

如何使用 reduce 创建我上面的新列表?

我试过:

var mymap = mydata.reduce((x, y) => 
    y.lob.map((lob, index) => {
       x.push({"item": lob, "timeRange": [y.startTimestamp, y.endTimestamp]})
    })
  ), [])

我也试过用地图。但是如果我有大数据,我认为 reduce 会有更好的性能。考虑到性能,我正在寻找最好的方法

而不是使用 reduce(), consider using flatMap()

const mydata = [
  { endTime: '123', startTime: '2323', lob: ['a', 'b', 'c'] },
  { endTime: '454', startTime: '3232', lob: ['a', 'b'] },
  { endTime: '4545', startTime: '2322', lob: ['c'] }
];

const result = mydata.flatMap(
  ({ lob, startTime, endTime }) => lob.map(
    item => ({ item, timeRange: [+startTime, +endTime] })
  )
);

console.log(result);

您可以使用 reduce

这样做

var mydata = [
  {"endTime": "123",
  "startTime": "2323",
  "lob" : ["a", "b", "c"]
  },
  {
  "endTime": "454",
  "startTime": "3232",
  "lob" : ["a", "b"]
  },
  {
  "endTime": "4545",
  "startTime": "2322",
  "lob" : ["c"]
  }
];

var newdata = mydata.reduce((acc, curr) => {
  curr.lob.forEach(el => {
    acc.push({ item: el, timeRange: [curr.endTime, curr.startTime] });
  });
  return acc;
}, []);
console.log(newdata);