3 回答
TA贡献1833条经验 获得超4个赞
我会使用减少
const data = [
{ fieldname: 'files0', originalname: 'Screenshot from 2020-05-23 01-52-30.png', },
{ fieldname: 'files0', originalname: 'Screenshot from 2020-05-22 08-44-05.png', },
{ fieldname: 'files1', originalname: 'Screenshot from 2020-05-30 11-36-42.png', },
{ fieldname: 'files1', originalname: 'Screenshot from 2020-05-30 11-36-36.png', },
{ fieldname: 'files1', originalname: 'Screenshot from 2020-05-30 11-36-31.png', }],
arr = data.reduce((acc, cur) => {
const idx = cur.fieldname.replace("files",""); // get 0, 1
if (acc[idx]) acc[idx].push(cur); // if already there, just push
else acc[idx] = [cur]; // otherwise initialise
return acc;
},[])
console.log(arr)
注意:组可以在 0 到 9 之间,具体取决于用户输入。
我假设没有漏洞,因为这可能会导致稀疏数组,所以
data = [
{ fieldname : 'files0' },
{ fieldname : 'files0' },
{ fieldname : 'files3' },
{ fieldname : 'files3' },
}
会创建一个数组
[
[ { fieldname : 'files0' }, { fieldname : 'files0' } ],
null,
null,
[ { fieldname : 'files3' }, { fieldname : 'files3' } ],
]
TA贡献1829条经验 获得超6个赞
我尽量不修改你的逻辑来做到这一点。
如果没有files2,filesArray[2] 将为undefined。
// Omit other fields
const req = {
files: [
{ fieldname: "files0", originalname: 'Screenshot from 2020-05-23 01-52-30.png'},
{ fieldname: "files0", originalname: 'Screenshot from 2020-05-22 08-44-05.png'},
{ fieldname: "files1", originalname: 'Screenshot from 2020-05-30 11-36-42.png'},
{ fieldname: "files1", originalname: 'Screenshot from 2020-05-30 11-36-36.png'},
{ fieldname: "files1", originalname: 'Screenshot from 2020-05-30 11-36-31.png'},
{ fieldname: "files3", originalname: 'Screenshot from 2020-05-30 11-36-42.png'},
{ fieldname: "files3", originalname: 'Screenshot from 2020-05-30 11-36-36.png'},
{ fieldname: "files3", originalname: 'Screenshot from 2020-05-30 11-36-31.png'}
]
}
let filesArray = []
for (let file of req.files) {
const thisFileGroup = parseInt(file.fieldname.match(/\d/g).join(''), 10);
if (!filesArray[thisFileGroup]) {
filesArray[thisFileGroup] = []
}
filesArray[thisFileGroup].push(file)
}
console.log(filesArray[2]) // will be undefined
console.log(filesArray[1]) // will be files1 array
console.log(filesArray)
TA贡献1820条经验 获得超2个赞
如果您不一定需要按索引排序files[index]
在这种情况下,你可以将Array.prototype.reduce()转换为Object。
您的对象将按属性(但不是按字母顺序)分组,其中包含一个数组,其中的项目具有相同的属性键。使用Object.values() (如果需要,还可以使用Array.prototype.forEach()) 迭代您的对象。fieldname
const data = [
{ fieldname: "files0", originalname: '0-a'},
{ fieldname: "files0", originalname: '0-b'},
{ fieldname: "files1", originalname: '1-a'},
{ fieldname: "files1", originalname: '1-b'},
{ fieldname: "files1", originalname: '1-c'},
];
const byFieldName = data.reduce((ob, d) => {
if (!ob.hasOwnProperty(d.fieldname)) ob[d.fieldname] = [];
ob[d.fieldname].push(d);
return ob;
}, {});
// console.log(byFieldName); // Uncomment to see how it looks like
console.log( Object.values(byFieldName) );
添加回答
举报