gpt4 book ai didi

javascript - 如何根据键搜索充满对象的数组并返回特定对象

转载 作者:行者123 更新时间:2023-12-03 10:36:58 25 4
gpt4 key购买 nike

我有一个对象数组:

    [{
"businessunit": [{
"Area": [{
"Asset": [{
"Wells": {
"Well": "Well 11"
},
"name": "Field 1"
}, {
"Wells": {
"Well": "Well 12"
},
"name": "Field 2"
}],
"name": "Archer"
}, {
"Asset": [{
"Wells": {
"Well": "Well 13"
},
"name": "Field 3"
}, {
"Wells": {
"Well": "Well 14"
},
"name": "Field 4"
}],
"name": "Anderson"
}],
"name": "North America"
}, {
"Area": [{
"Asset": [{
"Wells": {
"Well": "Well 15"
},
"name": "Field 5"
}, {
"Wells": {
"Well": "Well 16"
},
"name": "Field 6"
}],
"name": "ArcherSouth"
}, {
"Asset": [{
"Wells": {
"Well": "Well 17"
},
"name": "Field 7"
}, {
"Wells": {
"Well": "Well 18"
},
"name": "Field 8"
}],
"name": "AndersonSouth"
}],
"name": "South America"
}],
"name": "XYZ Oil Co"
}, {
"businessunit": [{
"Area": [{
"Asset": {
"Wells": {
"Well": "Well 19"
},
"name": "Field 9"
},
"name": "Archer"
}, {
"Asset": [{
"Wells": {
"Well": "Well 110"
},
"name": "Field 10"
}, {
"Wells": {
"Well": "Well 120"
},
"name": "Field 20"
}],
"name": "Anderson"
}],
"name": "North America"
}, {
"Area": {
"Asset": [{
"Wells": {
"Well": "Well 130"
},
"name": "Field 30"
}, {
"Wells": {
"Well": "Well 140"
},
"name": "Field 40"
}],
"name": "AndersonSouth"
},
"name": "South America"
}],
"name": "ABC Oil Co"
}];

我想根据提供的键进行搜索并返回包含该键的特定对象。

例如:如果我通过 key = "North America",我将得到:

{
"Area": [{
"Asset": [{
"Wells": {
"Well": "Well 11"
},
"name": "Field 1"
}, {
"Wells": {
"Well": "Well 12"
},
"name": "Field 2"
}],
"name": "Archer"
}, {
"Asset": [{
"Wells": {
"Well": "Well 13"
},
"name": "Field 3"
}, {
"Wells": {
"Well": "Well 14"
},
"name": "Field 4"
}],
"name": "Anderson"
}],
"name": "North America"
}

我试过了

function search(nameKey, myArray) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

但是由于我的对象数组再次包含更多对象数组。这没有帮助。

最佳答案

使用过滤器:

var results = $filter('filter')(myArray, { 'name': nameKey }, true)

关于javascript - 如何根据键搜索充满对象的数组并返回特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com