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

如何在深度嵌套的对象数组中基于level和userId字段生成唯一对象数组(Lodash或原生JavaScript实现)

如何基于level和userId字段从嵌套数组生成唯一对象数组?

嘿,这个需求我熟!你需要从嵌套的数组结构里提取所有output的元素,然后根据**level和userId的唯一组合**来去重,得到唯一的对象数组对吧?我给你准备了两种实用的实现方式,原生JS和Lodash的,都能搞定~

方法一:原生JavaScript实现

不需要额外依赖,用原生API就能完成。思路分两步:先把所有分散在values.output里的元素合并成一个大数组,再通过Set记录已出现的组合键来过滤重复项。

const data = [
  { values: { output: [], } },
  { values: { output: [
      { level: 1, userId: "810", },
      { level: 1, userId: "811", },
      { level: 2, userId: "811", },
    ], },
  },
  { values: { output: [
      { level: 1, userId: "810", },
    ], }
  },
  { values: { output: [
      { level: 1, userId: "810", },
      { level: 3, userId: "810", },
    ], }
  },
  { values: { output: [
      { level: 1, userId: "810", },
      { level: 3, userId: "810", },
    ], }
  }
];

// 1. 合并所有output数组的元素
const allItems = data.flatMap(item => item.values.output);

// 2. 根据level+userId的组合键去重
const seenKeys = new Set();
const uniqueOutput = allItems.filter(item => {
  const uniqueKey = `${item.level}-${item.userId}`;
  if (!seenKeys.has(uniqueKey)) {
    seenKeys.add(uniqueKey);
    return true;
  }
  return false;
});

console.log(uniqueOutput);
// 输出结果:
// [
//   { level: 1, userId: "810" },
//   { level: 1, userId: "811" },
//   { level: 2, userId: "811" },
//   { level: 3, userId: "810" }
// ]

方法二:Lodash实现

如果你的项目已经引入了Lodash,用它的工具函数会更简洁,代码可读性也更高:

const _ = require('lodash'); // 先确保已安装并引入Lodash

const data = [/* 你的原始数据 */];

// 1. 提取并合并所有output元素
const allItems = _.flatMap(data, item => item.values.output);

// 2. 基于level和userId的组合去重(两种写法任选其一)
// 写法一:用uniqWith自定义比较逻辑
const uniqueOutput = _.uniqWith(allItems, (objA, objB) => {
  return objA.level === objB.level && objA.userId === objB.userId;
});

// 写法二:用uniqBy生成唯一键
// const uniqueOutput = _.uniqBy(allItems, item => `${item.level}-${item.userId}`);

console.log(uniqueOutput);
// 同样得到你想要的唯一数组

两种方法的核心逻辑是一致的:先收集所有需要处理的元素,再通过**level和userId的组合**判断是否重复,最终得到去重后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:47:49