gpt4 book ai didi

javascript - 按对象键值搜索多级 JavaScript 数组

转载 作者:行者123 更新时间:2023-11-28 18:10:03 24 4
gpt4 key购买 nike

我有这个对象

  var myObj =   {
"sections": [{
"id": "s1",
"name": "my section no.1",
"sheets": [{
"id": "sheet1",
"questions": [{
"id": "q1",
"name": "my q",
"options": [{
"id": "o1",
"order_no": 1,
"name": "option 1"
}, {
"id": "o2",
"name": "option 2"
}]
}]
}]
}]
};

我想要函数通过 id 搜索这个数组所以searchById("o1") 应该返回

{"id": "o1","order_no": 1,"name": "option 1"}

并且 searchById("q1") 应该返回

{
"id": "q1",
"name": "my q",
"options": [{
"id": "o1",
"order_no": 1,
"name": "option 1"
}, {
"id": "o2",
"name": "option 2"
}]
}

请帮助我

最佳答案

你拥有的是对象,你可以使用for...in循环创建递归函数来返回结果。

var obj = {
"sections": [{
"id": "s1",
"name": "my section no.1",
"sheets": [{
"id": "sheet1",
"questions": [{
"id": "q1",
"name": "my q",
"options": [{
"id": "o1",
"order_no": 1,
"name": "option 1"
}, {
"id": "o2",
"name": "option 2"
}]
}]
}]
}]
}

function findObj(data, id) {
for (var i in data) {
if (i == 'id' && data[i] == id) return data
if (typeof data[i] == 'object' && findObj(data[i], id)) return findObj(data[i], id)
}
}

console.log(findObj(obj, 'o1'))
console.log(findObj(obj, 'q1'))

关于javascript - 按对象键值搜索多级 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828655/

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