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

如何使用for循环访问JSON中的item1、item2数组及其中的每个JSON对象?

JSON数组的两种遍历实现方案

假设你已经将给定的JSON字符串解析为JavaScript对象(命名为data),以下是针对两个需求的具体代码实现:

一、遍历单个数组中的每个JSON对象

普通for循环写法

const data = {
  "item1" : [{"index":"1"},{"id":"1","name":"npm","result":"expected text1"},{"id":"2","name":"yarn","result":"expected text2"},{"id":"3","name":"pnpm","result":"expected text3"}],
  "item2":  [{"index":"2"},{"id":"1","name":"npm","result":"expected text1 for item2"},{"id":"2","name":"yarn","result":"expected text2 for item 2"},{"id":"3","name":"pnpm","result":"expected text3 for item 2"}]
};

// 遍历item1数组内的所有对象
for (let i = 0; i < data.item1.length; i++) {
  const currentObj = data.item1[i];
  // 按需访问对象属性,比如打印name和result
  if (currentObj.name) {
    console.log(`工具:${currentObj.name},结果:${currentObj.result}`);
  } else {
    console.log(`索引项:${currentObj.index}`);
  }
}

// 遍历item2数组内的所有对象,写法完全一致
for (let i = 0; i < data.item2.length; i++) {
  const currentObj = data.item2[i];
  if (currentObj.name) {
    console.log(`工具:${currentObj.name},结果:${currentObj.result}`);
  } else {
    console.log(`索引项:${currentObj.index}`);
  }
}

更简洁的for...of循环写法

如果不需要数组索引,用for...of遍历更直观:

// 遍历item1的对象
for (const obj of data.item1) {
  console.log(obj); // 直接输出整个对象,或按需访问属性
}

// 遍历item2的对象
for (const obj of data.item2) {
  console.log(obj);
}

二、遍历JSON中的item1和item2数组本身

如果你需要批量处理data下的所有数组(比如item1、item2),可以先获取对象的键,再遍历每个键对应的数组:

普通for循环结合Object.keys

const arrayKeys = Object.keys(data); // 获取所有数组键:["item1", "item2"]

for (let i = 0; i < arrayKeys.length; i++) {
  const key = arrayKeys[i];
  const currentArray = data[key];
  
  console.log(`当前处理数组:${key}`);
  // 这里可以嵌套遍历数组内的对象,实现一次性处理所有数组及其内部元素
  for (const obj of currentArray) {
    console.log("数组内对象:", obj);
  }
}

for...in循环写法

// 遍历data的所有属性,直接拿到每个数组
for (const key in data) {
  // 过滤掉原型链上的属性,确保只处理自身定义的数组
  if (data.hasOwnProperty(key)) {
    const currentArray = data[key];
    console.log(`当前数组:${key}`);
    
    // 嵌套遍历数组内的对象
    for (const obj of currentArray) {
      console.log(obj);
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 03:23:14