我们正在尝试采用具有以下格式的数组:
[
{batchId: 123, files: [{fileName: 'fileA.txt'}, {fileName: 'fileB.txt'}],
{batchId: 456, files: [{fileName: 'fileC.txt'}, {fileName: 'fileD.txt'}],
]
并将其展平,表示为:
[
{batchId: 123, fileName: 'fileA.txt'},
{batchId: 123, fileName: 'fileB.txt'},
{batchId: 456, fileName: 'fileC.txt'},
{batchId: 456, fileName: 'fileD.txt'},
]
我们希望有一种更优雅的方法来使用预先存在的库(例如 Ramda 或 Lodash)转换此数据,但是任何 javascript 实现都可以。
最佳答案
您可以使用 reduce()
和 map()
方法并返回新数组。
const data = [
{batchId: 123, files: [{fileName: 'fileA.txt'}, {fileName: 'fileB.txt'}]},
{batchId: 456, files: [{fileName: 'fileC.txt'}, {fileName: 'fileD.txt'}]},
]
const result = data.reduce((r, e) => {
r.push(...e.files.map(o => Object.assign({}, o, {batchId: e.batchId})))
return r;
}, [])
console.log(result)
关于javascript - 展平数组,但使用子数组作为基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861298/