如何根据嵌套对象的值查找数组中父对象的索引
实现方案
可以使用数组的findIndex方法来实现需求,核心逻辑是遍历父对象数组,检查每个父对象的subCategories中是否存在匹配的子对象(通过比较name和value属性值),找到后返回对应的父对象索引。
代码示例
const data = [ { "category": "Diet", "subCategories": [ {name:'pescatarian', value: false }, {name:'vegan', value: false }, {name:'vegetarian', value: false } ] }, { "category": "Daily Exercise in Hours", "subCategories": [ {name:'one', value: false }, {name:'two', value: false }, {name:'three', value: false }, {name:'four', value: false } ] }, ]; // 目标子对象 const targetSubItem = {name:'pescatarian', value: false }; // 查找父对象索引 const parentIndex = data.findIndex(parent => { // 检查当前父对象的subCategories中是否存在匹配的子对象 return parent.subCategories.some(sub => sub.name === targetSubItem.name && sub.value === targetSubItem.value ); }); console.log(parentIndex); // 输出:0
关键说明
findIndex会遍历数组,返回第一个满足条件的元素索引,若没有匹配项则返回-1some方法用于检查子数组中是否存在符合条件的元素,找到匹配项后会立即停止遍历,提升效率- 不能直接用
sub === targetSubItem比较对象,因为对象是引用类型,必须通过属性值来判断是否匹配
扩展场景处理
如果存在多个父对象包含相同的子对象(即name和value都一致),findIndex只会返回第一个匹配的索引。如果需要获取所有匹配的父对象索引,可以改用reduce方法:
const allParentIndexes = data.reduce((acc, parent, index) => { if (parent.subCategories.some(sub => sub.name === targetSubItem.name && sub.value === targetSubItem.value )) { acc.push(index); } return acc; }, []); console.log(allParentIndexes); // 若有多个匹配则返回索引数组,否则返回空数组
内容的提问来源于stack exchange,提问作者pelotador.1
相关产品推荐
相关产品推荐

