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

如何在ES6或Lodash中根据选中项ID筛选获取目标对象

解决方案

你原来的代码用两次findIndex只能拿到外层数组的索引,没法直接获取包含group的完整目标对象。下面给你两种可行的方案,分别用ES6原生语法和Lodash实现:

ES6原生实现

方案1:分步查找合并

先定位包含目标ID的分组,再找到对应详情项,最后合并分组信息和详情:

const sampleData = [ 
  { group: "GroupA", details: [ { id: 123, name: "Mike", category: "Basketball" }, { id: 456, name: "John", category: "Golf" }] }, 
  { group: "GroupB", details: [ { id: 890, name: "Jenny", category: "Gymnastic" }, { id: 45611, name: "Santis", category: "Chess" }] }, 
];

const getFullItemById = (targetId) => {
  // 找到包含目标ID的分组对象
  const matchedGroup = sampleData.find(({ details }) => 
    details.some(detail => detail.id === targetId)
  );
  
  if (!matchedGroup) return null; // 未找到时返回null
  
  // 找到分组内对应的详情项
  const matchedDetail = matchedGroup.details.find(detail => detail.id === targetId);
  
  // 合并分组信息和详情
  return { group: matchedGroup.group, ...matchedDetail };
};

// 使用示例:传入选中的ID(比如123)
const result = getFullItemById(123);
console.log(result); 
// 输出:{ group: "GroupA", id: 123, name: "Mike", category: "Basketball" }

方案2:扁平化后查找

先把嵌套结构扁平化,直接生成包含group的所有项,再通过ID查找:

const getFullItemById = (targetId) => 
  sampleData
    .flatMap(({ group, details }) => 
      details.map(detail => ({ group, ...detail }))
    )
    .find(item => item.id === targetId) || null;

Lodash实现

利用Lodash的工具函数可以让代码更简洁:

方案1:扁平化后查找

const getFullItemById = (targetId) => 
  _.find(
    _.flatMap(sampleData, ({ group, details }) => 
      _.map(details, detail => ({ group, ...detail }))
    ),
    { id: targetId }
  );

方案2:嵌套查找合并

const getFullItemById = (targetId) => {
  const matchedGroup = _.find(sampleData, ({ details }) => 
    _.some(details, { id: targetId })
  );
  
  if (!matchedGroup) return null;
  
  const matchedDetail = _.find(matchedGroup.details, { id: targetId });
  return _.assign({ group: matchedGroup.group }, matchedDetail);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:12:49