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

如何提取嵌套数组中对象属性的唯一值并实现通用函数?

提取嵌套数组中指定属性的唯一值

需求说明

我有一个包含多个product对象的products数组,每个product对象下嵌套了categories数组。需要提取所有category对象里type属性的唯一值。目前已经有基于Lodash和原生JavaScript的实现,但希望编写一个接收属性路径参数、返回唯一值的通用函数,理想的简洁调用方式类似map(products, property("categories[].type"))。

现有实现代码

Lodash 实现

import { compact, flatten, map, property, uniq } from "lodash";

export const getAllTypes1 = (products) => {
  return uniq(
    compact(map(flatten(map(products, property("categories"))), "type"))
  );
};

原生 JavaScript 实现

export const getAllTypes2 = (products) => {
  const types = [];
  products.forEach((product) => {
    product.categories.forEach((category) => {
      if (!types.some((t) => t === category.type)) {
        types.push(category.type);
      }
    });
  });
  return types;
};

示例数据

const product1 = {
  name: 'Wilson Orange',
  price: 72.50,
  categories: [{
    type: 'flash sale',
    discountable: false,
  },{
    type: 'tennis',
    discountable: true,
  }]
};
const product2 = {
  name: 'Babolat Green',
  price: 65.50,
  categories: [{
    type: 'tennis',
    discountable: true,
  }]
};
const products = [product1, product2];

执行结果

const result = getAllTypes2(products);
console.log(result); // ["flash sale", "tennis"]

内容的提问来源于Stack Exchange,提问作者Null Head

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:06:35