遍历各级对象找出指定ID的对象
[
{
id: 8,
label: '配电间1',
chi: [{
id: 19,
label: '配电间12',
},
{
id: 110,
label: '配电间13',
},]
},
{
id: 9,
label: '配电间2',
},
{
id: 10,
label: '配电间3',
},
]
遍历数组找到与之匹配的id,并且拿到其中的项
找出编号为110的对象
function findObjectWithId(array, targetId) {
for (let i = 0; i < array.length; i++) {
const obj = array[i];
if (obj.chi) {
for (let j = 0; j < obj.chi.length; j++) {
const childObj = obj.chi[j];
if (childObj.id === targetId) {
return childObj;
}
}
}
}
return null;
}
const targetId = 110;
const foundObject = findObjectWithId(data, targetId);
if (foundObject) {
console.log("找到了对象:", foundObject);
} else {
console.log("没有找到匹配的对象");
}
原文地址:https://blog.csdn.net/galaxyJING/article/details/136388852
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!