JavaScript处理JSON API数据用filter筛选后读取id为undefined如何解决
问题原因
Array.filter()方法的返回值是所有符合条件的元素组成的新数组,不是单个匹配对象,你直接对数组调用.id属性自然会返回undefined。- 你直接打印整个数组能看到内容,是因为控制台会展开显示数组内的元素,但数组本身不存在id属性。
解决方案
方案1:修改为取数组首个元素的属性
如果确定只会有一个符合条件的元素,直接取数组下标为0的元素再访问id即可,修改代码如下:
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json' async function getID() { const response = await fetch(api_url); const data = await response.json(); const findsize = data.product.variants const jsonArray = findsize.filter(function(ele){ return ele.title == "8"; }); // 先判断数组不为空再访问,避免下标越界报错 if(jsonArray.length > 0) { console.log(jsonArray[0].id) } } getID();
方案2:使用Array.find()方法替代filter
如果你只需要获取第一个符合条件的单个对象,直接用find方法更合适,它会返回第一个匹配的元素而非数组,代码如下:
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json' async function getID() { const response = await fetch(api_url); const data = await response.json(); const findsize = data.product.variants // 直接返回第一个title为"8"的对象 const targetItem = findsize.find(function(ele){ return ele.title == "8"; }); // 匹配到元素再访问属性 if(targetItem) { console.log(targetItem.id) } } getID();
内容的提问来源于stack exchange,提问作者Lutrix
相关产品推荐
相关产品推荐

