原有格式
list=[
{
produceName:'测试1',
productCode:'cs01',
num:1,
...
},
{
produceName:'测试1',
productCode:'cs01',
num:4,
...
},
{
produceName:'测试2',
productCode:'cs02',
num:1,
...
},
]
要变成的格式
newList=[
{
produceName:'测试1',
child:[
{
productCode:'cs01',
num:1,
...
},
{
productCode:'cs01',
num:4,
...
}
]
},
{
produceName:'测试2',
child:[
{
productCode:'cs02',
num:1,
...
}
]
},
]
如何通过代码进行实现
const groupedProducts = [];
res.data.boxCodeInfoList.map(product => {
if (groupedProducts.some(grpProduct => grpProduct.proName === product.proName)) {
// 如果产品名已存在,则找到相应的产品对象,并添加码值和数值
const index = groupedProducts.findIndex(grpProduct => grpProduct.proName ===product.proName);
groupedProducts[index].childList.push({
boxCode: product.boxCode,
num: product.num,
boxCode: product.boxCode,
codeType: product.codeType,
proCode: product.proCode,
typeDesc: product.typeDesc
});
} else {
// 如果产品名不存在,则创建一个新的产品对象,并添加到数组中
groupedProducts.push({
proName: product.proName,
childList: [{
boxCode: product.boxCode,
num: product.num,
boxCode: product.boxCode,
codeType: product.codeType,
proCode: product.proCode,
typeDesc: product.typeDesc
}],
});
}
});
console.log(groupedProducts)
// 码值列表
this.boxCodeInfoList = groupedProducts