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

NodeJS无法读取JSON数据中嵌套[Object],如何打印beacons字段内容?

问题原因

  • Array.filter() 返回的是符合条件的元素组成的数组,而非单个对象。你直接访问arr1.beacons相当于读取数组的beacons属性,该属性不存在,值为undefined,所以循环不会执行。
  • Node.js的console.log默认仅打印2层嵌套结构,深度超过2的对象会被显示为[Object],因此你看不到beacons的内部内容。

解决方法

1. 正确获取匹配的单个设备对象

如果mac字段是唯一标识,更推荐用Array.find()方法,直接返回第一个匹配的对象,无需额外取下标:

const targetDevice = data.find(d => d.mac === "f008d155b4fe");

如果坚持用filter,需要手动取数组第一个元素:

const arr1 = data.filter(d => d.mac === "f008d155b4fe");
const targetDevice = arr1[0];

2. 遍历嵌套的beacons字段

beacons本身是数组类型,推荐用for...of或者forEach遍历:

// 先判断对象存在,避免空值报错
if (targetDevice) {
  // 遍历beacons数组
  for (const beacon of targetDevice.beacons) {
    // 可直接读取深层字段,比如beacon.ibeacon.uuid
    console.log('ibeacon的uuid值为:', beacon.ibeacon.uuid);
  }
}

3. 打印完整嵌套结构的调试方法

如果需要查看完整的嵌套内容,可选用以下两种方案:

  • 方案1:用JSON.stringify()格式化输出
// 第二个参数为null,第三个参数为缩进空格数,可实现格式化打印
console.log('完整设备信息:', JSON.stringify(targetDevice, null, 2));
  • 方案2:用console.dir()指定打印深度
// depth设为null会打印所有层级的内容
console.dir(targetDevice, { depth: null });

完整可运行示例代码

const data = [
  {"mac":"f008d155b4fe","deviceClass":["iBeacon","eddystone"],"model":"iBeacon","lastSeen":"1637655820","bevent":{"event":"update"},"rssi":{"last":-84},"beacons":[{"ibeacon":{"uuid":"783a69707094d0863b4a9bf94e555241","major":816,"minor":6,"power":0},"eddystone":{"power":0}}],"sensors":{"temperatureC":18,"voltage":3.299999952316284},"stats":{"uptime":"710","adv_cnt":"24","frame_cnt":7}},
  {"mac":"a0e6f8515eff","deviceClass":["arubaTag"],"firmware":{"bankA":"1.2-15"},"assetId":"0000-0000-0000","lastSeen":"1637655821","bevent":{"event":"update"},"rssi":{"last":-69},"sensors":{"battery":83},"stats":{"uptime":"82350","frame_cnt":3},"vendorName":"Aruba"}
];

const targetDevice = data.find(d => d.mac === "f008d155b4fe");
if (targetDevice) {
  console.log('完整设备信息:\n', JSON.stringify(targetDevice, null, 2));
  console.log('\n===== beacons详情 =====');
  targetDevice.beacons.forEach((item, idx) => {
    console.log(`第${idx+1}个beacon信息:`, item);
  });
} else {
  console.log('未找到匹配mac的设备');
}

内容的提问来源于stack exchange,提问作者Sitita Charuraks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:15:00