我需要通過 id 在深度嵌套的物件中查找名稱。也許lodash會有所幫助?如果我不知道我的陣列中有多少嵌套物件,那么最干凈的方法是什么?
這是示例陣列:
let x = [
{
'id': '1',
'name': 'name1',
'children': []
},
{
'id': '2',
'name': 'name2',
'children': [{
'id': '2.1',
'name': 'name2.1',
'children': []
},
{
'id': '2.2',
'name': 'name2.2',
'children': [{
'id': '2.2.1',
'name': 'name2.2.1'
},
{
'id': '2.2.2',
'name': 'name2.2.2'
}
]
}
]
},
{
'id': '3',
'name': 'name3',
'children': [{
'id': '3.1',
'name': 'name3.1',
'children': []
},
{
'id': '3.2',
'name': 'name3.2',
'children': []
}
]
}
];
例如,我有 id “2.2”,我需要它的名稱。謝謝
uj5u.com熱心網友回復:
從您的資料來看,這是一個可以幫助您輕松實作這一目標的解決方案
function findById(array, id) {
for (const item of array) {
if (item.id === id) return item;
if (item.children?.length) {
const innerResult = findById(item.children, id);
if (innerResult) return innerResult;
}
}
}
const foundItem = findById(x, "2.2");
console.log(foundItem);
/*
The result obtained here is: {id: '2.2', name: 'name2.2', children: Array(2)}
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/454354.html
標籤:javascript 数组 目的 罗达什
