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

如何在JavaScript中获取对象数组指定列的唯一值?

获取对象数组指定列的唯一值

基础实现方法

要提取指定列的唯一值,最简洁的方式是利用JavaScript的Set(自动去重特性),结合map提取目标字段:

针对你的size列示例:

const products = [
  {id: 1, size: 'small', weight: '1 kg', color: 'red', price: 100},
  {id: 2, size: 'small', weight: '1 kg', color: 'blue', price: 200},
  {id: 3, size: 'small', weight: '2 kg', color: 'green', price: 300},
  {id: 4, size: 'small', weight: '2 kg', color: 'yellow', price: 400},
  {id: 5, size: 'large', weight: '4 kg', color: 'pink', price: 500},
  {id: 6, size: 'large', weight: '4 kg', color: 'navy blue', price: 600},
  {id: 7, size: 'large', weight: '4 kg', color: 'cyan', price: 700},
  {id: 8, size: 'large', weight: '6 kg', color: 'amber', price: 800},
  {id: 9, size: 'large', weight: '6 kg', color: 'black', price: 900}
];

// 获取size列的唯一值
const uniqueSizes = [...new Set(products.map(item => item.size))];
console.log(uniqueSizes); // 输出: ['small', 'large']

核心逻辑:

  1. products.map(item => item.size):提取所有对象的size字段,得到含重复值的数组
  2. new Set(...):将数组转为Set结构,自动剔除重复元素
  3. [...Set]:把Set转回普通数组格式

在filter后链式调用实现

完全可以在你给出的filter操作后链式调用实现去重,只需要在filter之后追加map提取目标字段,再用Set去重即可:

假设selected是你的筛选条件对象(比如selected = {size: 'large'}),示例代码:

const selected = {size: 'large'};

const filteredUniqueWeights = [...new Set(
  products.filter(p => Object.keys(selected).every(k => selected[k] === p[k]))
    .map(item => item.weight)
)];

console.log(filteredUniqueWeights); // 输出: ['4 kg', '6 kg']

如果偏好Array.from替代扩展运算符,写法如下:

const filteredUniqueWeights = Array.from(
  new Set(
    products.filter(p => Object.keys(selected).every(k => selected[k] === p[k]))
      .map(item => item.weight)
  )
);

兼容旧环境的备选方案(不用Set)

如果需要兼容不支持Set的环境,可以用filter手动实现去重:

const uniqueSizes = products
  .map(item => item.size)
  .filter((size, index, arr) => arr.indexOf(size) === index);

逻辑是通过检查当前元素的索引是否等于它在数组中第一次出现的索引,保留唯一值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:25:38