typescript 从JavaScript中的对象数组中获取与键对应的唯一值

2ul0zpep  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(258)

我的数组看起来像这样

const arr1 = [
  {
    "Param1": "20",
    "Param2": "8",
    "Param3": "11",
    "Param4": "4",
    "Param5": "18",
    "Param6": "20",
    "Param7": "8"
  },
  {
    "Param6": "21",
    "Param7": "8",
    "Param8": "11",
    "Param9": "4",
    "Param10": "18"
  },
  {
    "Param1": "20",
    "Param2": "8",
    "Param3": "10"
  }
]

我想删除对象中存在的重复键值对。
预期结果:

arr1 = [
  {
    "Param1": "20",
    "Param2": "8",
    "Param3": "11",
    "Param4": "4",
    "Param5": "18",
    "Param6": "20",
    "Param7": "8"
  },
  {
    "Param6": "21",
    "Param8": "11",
    "Param9": "4",
    "Param10": "18"
  },
  {
    "Param3": "10"
  }
]

所需的输出是一个包含具有唯一键值对的对象的数组。我怎么才能得到这样的数组?

h6my8fg2

h6my8fg21#

算法:

  • {param: {value: boolean}}的格式创建一个Mapseen,它将指示是否已经看到具有此值的参数
  • 创建一个result数组来存储唯一的参数
  • 遍历输入数组,获取当前元素的键,并遍历它们。
  • 检查该值的参数是否已经被看到,如果是,则忽略;否则将其添加到result并将其标记为可见
  • 返回result数组。

实施:

const removeDuplicates = (arr: Record<string, string>[]) => {
    return arr.reduce<{
        seen: Record<string, Record<string, boolean>>;
        result: Record<string, string>[];
    }>(
        (acc, item) => {
            acc.result.push(
                Object.fromEntries(
                    Object.entries(item).filter(([key, value]) => {
                        acc.seen[key] = acc.seen[key] ?? {};
                        if (acc.seen[key][value]) return false;
                        acc.seen[key][value] = true;

                        return true;
                    }),
                ),
            );
            return acc;
        },
        { seen: {}, result: [] },
    ).result;
};

Playground

相关问题