我一直在寻找一种 JavaScript 方法来返回值的索引,但似乎找不到有效的方法。
我有以下代码:
let topics = [
{
id: 1,
name: 'Topic 1',
children: [
{
id: 2,
name: 'Subtopic 1.1' <---- Searching for this value
}
]
}
];
是否有一种方法可以在 topics
变量上使用一次在整个对象数组中搜索 Subtopic 1.1
的值,然后返回父索引,在这种情况下为 0。
答案 0 :(得分:1)
没有一个函数,但是您可以在 Array.prototype.find
中嵌套一个 Array.prototype.findIndex
函数而没有问题来实现您想要的(findIndex
搜索父项,{{ 1}} 来搜索孩子):
find
答案 1 :(得分:0)
没有
您将遍历子项,然后使用嵌套循环遍历每个索引值。如果找到匹配项,则来自父循环的递增变量就是您想要的索引。
编辑:代码示例
let topics = [
{
id: 1,
name: 'Topic 1',
children: [
{
id: 2,
name: 'Subtopic 1.1'
},
{
id: 2,
name: 'Subtopic 3.1'
},
{
id: 2,
name: 'Subtopic 1.1'
},
{
id: 2,
name: 'Subtopic 2.1'
},
{
id: 2,
name: 'Subtopic 1.1'
}
]
}
];
for (let i in topics[0]["children"]) {
if (topics[0]["children"][i]["name"] == "Subtopic 1.1") {
console.log(i)
}
}
答案 2 :(得分:0)
您可以使用array.findIndex()
let topics = [{
id: 1,
name: 'Topic 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'))