JS遍历JSON数组:筛选seen_device类型数据并去重
问题解决:提取API响应中指定类型的条目并去重
问题背景
我通过API调用获取JSON格式的响应数据,结果存在重复条目。需要遍历该数据,仅提取type为"seen_device"的条目,并展示其value和timestamp字段。
原API请求代码
var url = "api call"; var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Authorization", "Bearer $token"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { console.log(xhr.status); console.log(xhr.responseText); }}; xhr.send();
API响应示例
{ "next": "url", "data": [ { "profile_id": "00000000-0000-0000-0000-000000012f44", "value": { "signal": 0.61, "connection": "radio_low_power", "profile_id": "00000000-0000-0000-0000-000000013ee4" }, "timestamp": "2022-07-22T14:52:37.359000Z", "type": "seen_device" }, { "profile_id": "00000000-0000-0000-0000-000000012f44", "value": 0.61, "timestamp": "2022-07-22T14:52:37.359000Z", "type": "connection_signal" }, { "profile_id": "00000000-0000-0000-0000-000000012f44", "value": { "signal": 0.58, "connection": "radio_low_power", "profile_id": "00000000-0000-0000-0000-000000013ee4" }, "timestamp": "2022-07-22T14:37:32.096000Z", "type": "seen_device" }, ... ] }
尝试的错误代码
for(let i = 0; i < xhr.length; i++) { let obj = xhr.responseText[i]; console.log("hello"); console.log(xhr.responseText.data); }
问题分析与修正方案
你的代码存在两个核心问题:
xhr.responseText是字符串格式,不是数组,不能直接用下标访问,也没有xhr.length这个属性- 没有把JSON字符串解析成可操作的JavaScript对象
下面是修正后的完整代码:
xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // 把响应字符串解析成JSON对象 const response = JSON.parse(xhr.responseText); const filteredDevices = []; const uniqueMarker = new Set(); // 遍历数据数组,筛选目标条目并去重 response.data.forEach(item => { if (item.type === "seen_device") { // 生成唯一标识(可根据实际重复规则调整,比如仅用timestamp) const uniqueKey = `${item.timestamp}-${item.value.profile_id}`; if (!uniqueMarker.has(uniqueKey)) { uniqueMarker.add(uniqueKey); // 只提取需要的字段 filteredDevices.push({ value: item.value, timestamp: item.timestamp }); } } }); // 输出最终结果 console.log("筛选并去重后的seen_device条目:"); console.log(filteredDevices); } };
关键说明
- 解析响应:用
JSON.parse()将字符串转为对象,才能正常访问response.data数组 - 筛选逻辑:通过
item.type === "seen_device"精准过滤目标类型条目 - 去重逻辑:用
Set存储唯一标识,避免重复添加相同条目,可根据实际重复规则调整唯一标识的生成方式 - 结果提取:只保留需要的
value和timestamp字段,按需输出
内容的提问来源于stack exchange,提问作者CSanchez
相关产品推荐
相关产品推荐

