怎么遍历json对象集合

2024-04-18

在JavaScript中,可以使用for..in循环来遍历JSON对象集合。下面是一个示例代码:

let jsonObj = {
  "name": "Alice",
  "age": 25,
  "city": "New York"
};

for (let key in jsonObj) {
  console.log(key + ": " + jsonObj[key]);
}

上面的代码会依次打印出JSON对象中的每个属性名和对应的值。如果JSON对象是一个数组,可以使用forEach方法来遍历每个元素。示例代码如下:

let jsonArray = [
  {
    "name": "Alice",
    "age": 25,
    "city": "New York"
  },
  {
    "name": "Bob",
    "age": 30,
    "city": "Los Angeles"
  }
];

jsonArray.forEach((obj) => {
  for (let key in obj) {
    console.log(key + ": " + obj[key]);
  }
});

以上是两种常见的遍历JSON对象集合的方式。根据具体情况和需求,可以选择合适的方法来遍历JSON对象集合。