经常会遇到数据处理的情况,其实处理起来并不难,只是思维模式的问题,思考对了就很简单
源数据格式
let oldObj = [
{id: 0, parentId: 'AA', type: "M"},
{id: 1, parentId: 'AA', type: "M"},
{id: 2, parentId: 'CC', type: "M"},
{id: 3, parentId: 'AA', type: "M"},
{id: 4, parentId: 'BB', type: "M"},
{id: 5, parentId: 'AA', type: "M"},
{id: 6, parentId: 'BB', type: "M"},
{id: 7, parentId: 'AA', type: "M"},
{id: 8, parentId: 'BB', type: "M"},
{id: 9, parentId: 'CC', type: "M"},
{id: 10, parentId: 'BB', type: "M"},
{id: 11, parentId: 'CC', type: "M"}
]
我们需要对源数据处理,根据相同parentId值合并id到一个数组中,并用parentId作为新对象的key,id的数组为value,即下面的格式:
let newObj = {
"AA":[1,3,5,7],
"CC":[9,11],
"BB":[6,8,10]
}
方法:
let newObj = new Object;
for(let i in oldObj){
if(newObj[oldObj[i].parentId]){
//新对象存在这个key
newObj[oldObj[i].parentId].push(oldObj[i].id)
}else{
//新对象不存在这个key
newObj[oldObj[i].parentId] = new Array;
}
}
console.log(newObj)
console.log(JSON.stringify(newObj))
网友评论