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

在JavaScript/jQuery中访问嵌套JSON未知父级的指定子对象

嘿,这个需求我懂!你需要根据给定的index值数组(比如[0, 3])找到嵌套JSON里对应rows对象的cells属性,还不想用forEach循环。那咱们分几种情况来解决,优先给你无循环的高效方案,再备上循环的选项~

方案1:预构建映射表(无循环访问,强烈推荐)

核心思路是先把rows数组转换成一个以index为键、对应行对象为值的映射表。这样后续不管要取多少个index的cells,都能直接通过键快速访问,完全不用再遍历原数组。这种方式只需要一次遍历构建映射,后续所有访问都是O(1)的效率,特别适合需要多次查询的场景。

代码示例:

// 先构建index到row对象的映射表
const rowIndexMap = Object.fromEntries(data.rows.map(row => [row.index, row]));

// 定义你要获取的目标index数组
const targetIndexes = [0, 3];

// 直接通过映射表获取对应的cells属性
const targetCells = targetIndexes.map(index => rowIndexMap[index]?.cells);

console.log(targetCells);
// 输出结果就是index为0和3的rows对应的cells数组

解释一下:

  • Object.fromEntries()可以把二维键值对数组转换成对象,这里我们把每个row的index作为键,row本身作为值。
  • ?.是可选链操作符,能避免当目标index不存在时抛出错误,会返回undefined。
  • 后续如果要单独获取某个index的cells,直接写rowIndexMap[3].cells就行,完全不用循环。
方案2:单次查询的无循环写法(利用数组内置方法)

如果只是单次查询,不想提前构建映射表,也可以用Array.prototype.find来实现。虽然find内部还是会遍历数组,但写法上没有显式的循环:

const targetIndexes = [0, 3];

const targetCells = targetIndexes.map(index => 
  data.rows.find(row => row.index === index)?.cells
);

console.log(targetCells);

注意:这个方法适合查询次数少的场景,如果要查询多个index,每个index都会触发一次数组遍历,效率不如方案1。

备选方案:for循环(完全避免高阶数组方法)

如果你连map、find这些高阶方法都不想用,那可以用普通的for循环来实现,分两种写法:

写法1:先构建映射表再查询

const targetIndexes = [0, 3];
const targetCells = [];

// 手动用for循环构建映射表
const rowIndexMap = {};
for (let i = 0; i < data.rows.length; i++) {
  const row = data.rows[i];
  rowIndexMap[row.index] = row;
}

// 遍历目标index数组,收集对应cells
for (let i = 0; i < targetIndexes.length; i++) {
  const index = targetIndexes[i];
  if (rowIndexMap[index]) {
    targetCells.push(rowIndexMap[index].cells);
  }
}

console.log(targetCells);

写法2:直接遍历rows数组收集目标

const targetIndexes = [0, 3];
const targetCells = [];

for (let i = 0; i < data.rows.length; i++) {
  const row = data.rows[i];
  // 检查当前row的index是否在目标数组里
  if (targetIndexes.includes(row.index)) {
    targetCells.push(row.cells);
  }
}

console.log(targetCells);

内容的提问来源于stack exchange,提问作者bharathy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:55:22