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

如何将API返回的重复JS对象数组转换为去重键值对对象?

问题:将含重复项的JS对象数组去重转换为键值对对象

我从API获取到一组带重复项的JS对象数组,每个对象都有value和label属性,示例输入如下:

const rawData = [
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type1', label: "Pieds dans l'eau"},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type3', label: 'Foodies'},
  {value: 'type1', label: "Pieds dans l'eau"},
  {value: 'type1', label: "Pieds dans l'eau"},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type4', label: 'Grand air & Nature'},
  {value: 'type1', label: "Pieds dans l'eau"},
  {value: 'type2', label: 'Patrimoine & Culture'},
  {value: 'type3', label: 'Foodies'}
];

需要把它转换成去重后的键值对对象,用来构建选择器,目标格式如下:

const arr = {
    type1 : 'Pieds dans l\'eau',
    type2 : 'Patrimoine & Culture',
    type3 : 'Foodies',
    type4 : 'Grand air & Nature',
};

解决方案

方法1:用Array.reduce()实现(最简洁)

直接用reduce遍历数组,把每个对象的value当作键、label当作值存入结果对象。因为对象的键是唯一的,重复的value会自动覆盖,最后就能得到去重后的键值对:

const rawData = [/* 你的原始数组 */];
const result = rawData.reduce((acc, item) => {
  acc[item.value] = item.label;
  return acc;
}, {});

console.log(result);
// 输出结果:
// {
//   type1: "Pieds dans l'eau",
//   type2: "Patrimoine & Culture",
//   type3: "Foodies",
//   type4: "Grand air & Nature"
// }

方法2:用Set结合forEach

先提取所有不重复的value,再遍历原始数组填充对应的label,适合需要先明确所有唯一值的场景:

const rawData = [/* 你的原始数组 */];
const uniqueValues = new Set(rawData.map(item => item.value));
const result = {};

rawData.forEach(item => {
  if (uniqueValues.has(item.value)) {
    result[item.value] = item.label;
    uniqueValues.delete(item.value); // 存完就删掉,避免重复处理
  }
});

console.log(result);

特殊场景处理

如果原始数组里出现**相同value但不同label**的情况,上面的方法会保留最后一次出现的label。要是需要处理这种冲突,可以按需调整逻辑:

  • 保留第一个出现的label:
const result = rawData.reduce((acc, item) => {
  // 只有键不存在时才赋值
  if (!acc.hasOwnProperty(item.value)) {
    acc[item.value] = item.label;
  }
  return acc;
}, {});
  • 其他需求比如抛出提示、合并label等,都可以在这个基础上修改判断逻辑。

内容的提问来源于stack exchange,提问作者Paul-H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:15:26