如何用JavaScript按名称过滤接口返回对象,获取指定字段值?
按名称过滤数组项获取在线用户数
你当前通过数组索引items[1]获取Forms的在线用户数,但这个位置可能变化导致代码失效,完全可以通过按名称过滤数组项来实现需求,不用依赖固定索引。
解决方案:使用数组find方法
Array.find()可以遍历数组,返回第一个符合条件的元素,完美适配你的场景。修改后的代码如下:
fetch('http://endpoint', requestOptions) .then((response) => response.json()) .then((result) => { // 查找name为"Forms"的项 const formsItem = result.resource.items.find(item => item.name === "Forms"); // 先判断是否找到该项,避免报错 if (formsItem) { const onlineUsers = formsItem.onlineUsers >= 1; console.log(onlineUsers); // 这里可以写你需要执行的逻辑 } else { console.log("未找到名称为Forms的项"); } }) .catch((error) => console.log('error', error));
代码说明
find(item => item.name === "Forms"):遍历items数组,返回第一个name等于"Forms"的对象- 增加
if (formsItem)判断:防止数组中没有"Forms"项时出现Cannot read property 'onlineUsers' of undefined的错误
这样不管Forms在items数组中的位置怎么变,都能准确获取到它的onlineUsers值。
内容的提问来源于stack exchange,提问作者gmcode
相关产品推荐
相关产品推荐

