我具有以下对象结构:
[{
directory: 'dir1',
fileName: 'file1.png'
},
{
directory: 'dir2',
fileName: 'file2.png'
},
{
directory: 'dir1',
fileName: 'file2.png'
},
{
directory: 'dir1',
fileName: 'file3.png'
},
{
directory: 'dir2',
fileName: 'test.png'
}
}]
我想对该信息进行后处理以产生以下分组:
{
"dir1": ["file1.png", "file2.png"],
"dir2": ["file1.png", "file2.png"],
}
我只使用普通的旧式JS。完成这样的事情的最佳方法是什么?
答案 0 :(得分:1)
const data = [{
directory: 'dir1',
fileName: 'file1.png'
},
{
directory: 'dir2',
fileName: 'file2.png'
},
{
directory: 'dir1',
fileName: 'file2.png'
},
{
directory: 'dir1',
fileName: 'file3.png'
},
{
directory: 'dir2',
fileName: 'test.png'
}
];
const result = data.reduce((acc, {
directory,
fileName
}) => {
acc[directory] ? acc[directory].push(fileName) : (acc[directory] = [fileName]);
return acc;
}, {})
console.log(result)