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

如何循环遍历JSON响应内placeListings对象并提取Name属性值

问题根源

你当前的循环逻辑存在两个核心错误:

  • 接口返回的res是普通对象,不是数组类型,不存在length属性,原有for循环的终止条件i < res.length永远不成立,循环不会正常执行。
  • res.placeListings下的OBJ1/OBJ2/OBJ3是动态生成的键名,硬编码写死res.placeListings.OBJ1.Name只能固定取到第一个对象的Name值,无法适配动态键场景。
实现方案

以下三种方案均可实现需求,按需选择即可:

方案1:Object.values 直接遍历属性值(最简洁,推荐)

不需要关心动态键名,直接拿到placeListings下所有子对象组成的数组遍历即可:

for (const place of Object.values(res.placeListings)) {
  console.log("NAME: " + place.Name);
}

方案2:for...in 遍历对象键名

直接遍历对象的可枚举属性,通过动态键取值,加原型属性校验避免异常:

for (const key in res.placeListings) {
  // 过滤原型链上继承的属性,只处理对象自身的键
  if (Object.prototype.hasOwnProperty.call(res.placeListings, key)) {
    console.log("NAME: " + res.placeListings[key].Name);
  }
}

方案3:Object.keys 转成键名数组后按索引遍历

和你原来写的索引式for循环逻辑兼容度最高:

const listingKeys = Object.keys(res.placeListings);
for (let i = 0; i < listingKeys.length; i++) {
  const currentItem = res.placeListings[listingKeys[i]];
  console.log("NAME: " + currentItem.Name);
}
执行效果

以上任意一种方案运行后,都会正确输出所有Name字段值:

NAME: place 1
NAME: place 2
NAME: place 3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 02:57:25