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

从API获取的数组对象取值异常问题(JavaScript)

问题分析与解决

核心问题

你代码里的错误在于:filter方法本身返回的就是一个数组,而你用array.push(result)把这个数组整个作为元素塞进了array里,导致array变成了嵌套数组(结构是[[筛选后的对象1, 筛选后的对象2]])。当你访问array[0].attributes时,实际是在访问外层数组的第一个元素(也就是那个筛选后的数组)的attributes属性,而数组本身没有这个属性,所以返回undefined。

修复方案

方案1:直接赋值(推荐)

不需要额外创建空数组再push,直接把filter的结果赋值给array:

let arrayFetch = fetchData.included;
const array = arrayFetch.filter(res => res.type === "wanted-type");
// 现在array就是筛选后的对象数组,直接访问即可
console.log(array[0].attributes); // 正常输出{ stats: { name: "name1" } }

方案2:如果需要保留原array的其他元素,用扩展运算符push

如果array原本还有其他内容,需要追加筛选结果,用扩展运算符把数组元素逐个push:

let arrayFetch = fetchData.included;
let array = [];
const result = arrayFetch.filter(res => res.type === "wanted-type");
if(result.length > 0) { // 注意:数组即使为空,if(result)也会返回true,因为数组是引用类型,要判断长度
  array.push(...result);
}
console.log(array[0].attributes); // 正常输出

针对你最初需求的优化(查找name为name1的对象)

如果你最初是想找到name为name1的对象,可以在find里加上属性存在性检查,避免因为没有attributes或stats而报错:

const target = fetchData.included.find(value => 
  value.type === "wanted-type" && 
  value.attributes?.stats?.name === "name1"
);
// 使用可选链操作符?.,如果中间属性不存在会直接返回undefined,不会抛出错误
console.log(target?.attributes);

内容的提问来源于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 06:34:54