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

如何在JavaScript中查找嵌套对象数组中的指定值?

解决数组元素查找问题

你的代码有两个核心问题导致无法正常运行:

  1. for...in不适合遍历数组:它会遍历数组的所有可枚举属性(包括原型链上的属性),容易出现意外结果。
  2. 语法与作用域错误:if语句没有用大括号完整包裹代码块,且全局环境下不能直接使用return——return只能在函数内部生效。

下面提供几种可靠的解决方案:

方案一:使用数组find方法(推荐)

这是最简洁高效的方式,find会遍历数组并返回第一个符合条件的元素,找不到则返回undefined:

const targetItem = array.find(item => item.attributes.name === "some-other-name");

方案二:使用for...of循环

如果需要在遍历过程中执行额外操作,for...of是更直观的选择:

let targetItem;
for (const item of array) {
  if (item.attributes.name === "some-other-name") {
    targetItem = item;
    break; // 找到目标后立即退出循环,提升效率
  }
}

方案三:修复原for...in代码(不推荐)

如果一定要用for...in,需要添加hasOwnProperty判断避免遍历原型属性,同时修正语法和作用域问题:

let targetItem;
for (let i in array) {
  if (array.hasOwnProperty(i)) {
    if (array[i].attributes.name === "some-other-name") {
      targetItem = array[i];
      break;
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 05:59:50