You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据嵌套对象的值查找数组中父对象的索引

实现方案

可以使用数组的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会遍历数组,返回第一个满足条件的元素索引,若没有匹配项则返回-1
  • some方法用于检查子数组中是否存在符合条件的元素,找到匹配项后会立即停止遍历,提升效率
  • 不能直接用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:55:18