JSON 重组合并,已知父子关系resourceId,不知道怎么循环?

JSON 重组合并,已知父子关系resourceId,不知道怎么循环?

原始数据:
let arr1 = [

    {

"resourceId": "StartEvent_1", //太爷爷

"outgoing": [{

"resourceId": "Flow_0xcdvi2"//爷爷ID

}],

childList:[]

},

{

"resourceId": "Flow_0xcdvi2", //爷爷

"outgoing": [{

"resourceId": "userrenwu"//父亲ID

}],

childList:[]

},

{

"resourceId": "userrenwu", //父亲

"outgoing": [{

"resourceId": "Flow_0vodf2r"//儿子ID

}],

childList:[]

},

{

"resourceId": "Event_14beign",//孙

"outgoing": [],

childList:[]

},

{

"resourceId": "Flow_0vodf2r", //儿子

"outgoing": [{

"resourceId": "Event_14beign"//孙ID

}],

childList:[]

},

{

"resourceId": "StartEvent_2", //太爷爷的弟弟

"outgoing": [{

"resourceId": "Flow_0xcdvi33"//太爷爷的儿子ID

}],

childList:[]

},

]

想要的结构是:

let arr1 = [

    {

"resourceId": "StartEvent_1", //太爷爷

"outgoing": [{

"resourceId": "Flow_0xcdvi2"//爷爷ID

}],

childList:[

{

"resourceId": "Flow_0xcdvi2", //爷爷

"outgoing": [{

"resourceId": "userrenwu"//父亲ID

}],

childList:[

{

"resourceId": "userrenwu", //父亲

"outgoing": [{

"resourceId": "Flow_0vodf2r"//儿子ID

}],

childList:[

{

"resourceId": "Flow_0vodf2r", //儿子

"outgoing": [{

"resourceId": "Event_14beign"//孙ID

}],

childList:[

{

"resourceId": "Event_14beign",//孙

"outgoing": [],

childList:[]

}

]

}

]

}

]

}

]

},

{

"resourceId": "StartEvent_2", //太爷爷的弟弟

"outgoing": [{

"resourceId": "Flow_0xcdvi33"//太爷爷的儿子ID

}],

childList:[]

},

]


回答:

传入的参数需要先进行深拷贝, 保证不改变原数据。

setTree这个方法利用了JS引用类型的特点,v 和 child最终会同步, filter最后只需要过滤出需要的层级就OK了。

function setTree(arr) {

const tree = arr.filter((v) => {

const child = arr.find((x) => x.resourceId === v.outgoing[0]?.resourceId);

if (child) {

v.childList.push(child);

}

return v.resourceId.includes('StartEvent');

});

return tree;

}

const newArr = setTree(JSON.parse(JSON.stringify(arr1)));

以上是 JSON 重组合并,已知父子关系resourceId,不知道怎么循环? 的全部内容, 来源链接: utcz.com/p/935399.html

回到顶部