如何解决JavaScript 搜索对象数组并返回父对象的索引
我一直在寻找一种 JavaScript 方法来返回值的索引,但似乎找不到有效的方法。
let topics = [
{
id: 1,name: 'Topic 1',children: [
{
id: 2,name: 'Subtopic 1.1' <---- Searching for this value
}
]
}
];
是否有一种方法可以在 topics
变量上使用一次在整个对象数组中搜索 Subtopic 1.1
的值,然后返回父索引,在这种情况下为 0。
解决方法
没有一个函数,但是您可以在 Array.prototype.find
中嵌套一个 Array.prototype.findIndex
函数而没有问题来实现您想要的(findIndex
搜索父项,{{ 1}} 来搜索孩子):
find
没有
您将遍历子项,然后使用嵌套循环遍历每个索引值。如果找到匹配项,则来自父循环的递增变量就是您想要的索引。
编辑:代码示例
let topics = [
{
id: 1,name: 'Topic 1',children: [
{
id: 2,name: 'Subtopic 1.1'
},{
id: 2,name: 'Subtopic 3.1'
},name: 'Subtopic 1.1'
},name: 'Subtopic 2.1'
},name: 'Subtopic 1.1'
}
]
}
];
for (let i in topics[0]["children"]) {
if (topics[0]["children"][i]["name"] == "Subtopic 1.1") {
console.log(i)
}
}
,
您可以使用array.findIndex()
let topics = [{
id: 1,children: [{
id: 1,name: 'Subtopic 1.2'
},{
id: 4,name: 'Subtopic 1.4'
},{
id: 2,name: 'Subtopic 1.1'
}]
}];
const findIndexOf = val => {
return topics[0].children.findIndex(e => e.name.trim() === val.trim())
}
console.log(findIndexOf('Subtopic 1.1'))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。