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

如何用ES6/lodash在嵌套对象数组中按device_id匹配查找父对象?

实现方案:筛选包含指定device_id的数组元素

纯ES6实现

结合Array.filter()、Object.values()和Array.some()即可完成需求:

const targetDeviceId = 'abc';

// 筛选符合条件的数组元素
const result = entities.filter(entity => {
  // 提取当前元素下所有嵌套对象
  const nestedObjects = Object.values(entity);
  // 检查是否存在任意嵌套对象的device_id匹配目标值
  return nestedObjects.some(obj => obj.device_id === targetDeviceId);
});

console.log(result);

逻辑说明

  • entities.filter():遍历数组,仅保留返回true的元素
  • Object.values(entity):将未知键的对象转换为值数组,直接获取所有嵌套对象
  • nestedObjects.some(...):只要有一个嵌套对象的device_id匹配目标值,就判定当前数组元素符合条件

Lodash实现

利用lodash的工具方法可以让代码更简洁,支持两种写法:

基础写法

const targetDeviceId = 'abc';

const result = _.filter(entities, entity => {
  return _.some(_.values(entity), obj => obj.device_id === targetDeviceId);
});

console.log(result);

链式调用写法

const targetDeviceId = 'abc';

const result = _.chain(entities)
  .filter(entity => _.some(_.values(entity), { device_id: targetDeviceId }))
  .value();

逻辑说明

  • _.filter():与ES6原生filter功能一致,用于数组筛选
  • _.values(entity):等价于Object.values(),提取对象的所有值组成数组
  • _.some(..., { device_id: targetDeviceId }):lodash的some方法支持直接传入匹配对象,简化条件判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:05:01