查找x深度Javascript数组中的元素



是否可以在深度x的数组中使用find()方法?

例如,假设我有以下对象数组,称其为test:
[
{
"id": "1",
"title": "First",
},
{
"id": "2",
"title": "Second",
"movies": [
{
"id": "3",
"title": "Happy Gilmore",
"Actors": [
{
"id": "4",
"title": "John Doe",
},
{
"id": "5",
"title": "Jane Doe",
},
],
"Producers": [
{
"id": "6",
"title": "Max Smith",
},
{
"id": "7",
"title": "Richard Rocky",
},
],
},
{
"id": "10",
"title": "Billy Madison",
"Actors": [
{
"id": "40",
"title": "John Smith",
},
{
"id": "50",
"title": "Alex Doe",
},
],
"Producers": [
{
"id": "60",
"title": "Bob Smith",
},
{
"id": "70",
"title": "Polly Rocky",
},
],
}
]
}
]

假设我正在寻找"2"id。我可以使用find()方法搜索数组的第一层,并通过执行test.find(element => element.id === "2")返回所需的对象。

但是,假设我现在正在寻找id为4的事件。从上面的JSON中可以看到,该元素位于test的子数组中。因此,是否有一种方法,我仍然可以通过test搜索找到id=4的元素?

find不能这样做,但是您可以在递归方法中使用它:

function findDeep(arr, predicate) {
let res = arr.find(predicate);
if (res !== undefined) return res;
for (let obj of arr) {
for (let value of Object.values(Object(obj)).filter(Array.isArray)) {
res = findDeep(value, predicate);
if (res !== undefined) return res;
}
}
}
let test = [{"id": "1","title": "First",},{"id": "2","title": "Second","movies": [{"id": "3","title": "Happy Gilmore","Actors": [{"id": "4","title": "John Doe",},{"id": "5","title": "Jane Doe",},],"Producers": [{"id": "6","title": "Max Smith",},{"id": "7","title": "Richard Rocky",},],},{"id": "10","title": "Billy Madison","Actors": [{"id": "40","title": "John Smith",},{"id": "50","title": "Alex Doe",},],"Producers": [{"id": "60","title": "Bob Smith",},{"id": "70","title": "Polly Rocky",},],}]}];
let res = findDeep(test, obj => obj.id == "4");
console.log(res);

最新更新