将数组里的对象中相同的值提取出来进行分组,以该字段相同的为一组进行处理
待处理的数据:为常见的表格列表数据,数组中有对象,key的值为平铺的。
下面为举例的json格式
{
"data": [
{
"boarPigID": "xxxx",
"childIndex": 0,
"breedIndex": 0,
"sowPigID": 1111
},
{
"boarPigID": "xxxx",
"childIndex": 0,
"breedIndex": 0,
"sowPigID": 2222
},
{
"boarPigID": "xxxx",
"childIndex": 0,
"breedIndex": 0,
"sowPigID": 3333
},
{
"boarPigID": "xxxx",
"childIndex": 0,
"breedIndex": 0,
"sowPigID": 4444
}
]
}
后端期望在传参处理成这样传参(demo ,模拟)
也就是说 以 sowPigID 进行分组,提起出相同的sowPigID 。
"details": [
{
"sowPigID": null,
"extends": [
{
"boarPigID": null,
"childIndex": 0,
"breedIndex": 0
},
{
"boarPigID": null,
"childIndex": 0,
"breedIndex": 0
}
{
"boarPigID": null,
"childIndex": 0,
"breedIndex": 0
}
]
}
],
实现代码如下:
- this.listInstance 为当前待处理的数组
let _set = new Set()
let _arr = []
this.listInstance.forEach(item => {
_set.add(item.mpigid)
});
[..._set].forEach((item) => {
_arr.push({
"sowPigID": item,
"extends": []
})
})
console.log(' _arr', _arr)
_arr.forEach((itm) => {
this.listInstance.forEach(item => {
if (item.sowPigID== itm.sowPigID) {
itm.extends.push({
"boarPigID": item.boarPigID,
"childIndex": item.childindex,
"breedIndex": item.breedindex,
})
}
});
})