首页 > 解决方案 > 如何在对象数组中只包含一次值?

问题描述

我有这个对象数组。

[
  {
    tier1: "Normal",
    tier2: "none",
    tier3: "none",
    tier4: "none",
    tier5: "none",
  },
  {
    tier1: "Urgent",
    tier2: "GCC & Labour",
    tier3: "new",
    tier4: "Cancellation",
    tier5: "Cancellation",
  },
  {
    tier1: "Urgent",
    tier2: "Foreigner",
    tier3: "renew",
    tier4: "Cancellation",
    tier5: "none",
  },
]

我只需要一次获取tier1,tier2和values 。tier3 tier4tier5

所以假设在上面的例子tier1中有Normal一次和Urgent两次,所以它将在下一个元素中被删除。tier5hasnone在第一个元素中,因此将从最后一个元素中删除,因为它已经存在。

输出将是

[
  {
    tier1: "Normal",
    tier2: "none",
    tier3: "none",
    tier4: "none",
    tier5: "none",
  },
  {
    tier1: "Urgent",
    tier2: "GCC & Labour",
    tier3: "new",
    tier4: "Cancellation",
    tier5: "Cancellation",
  },
  { tier2: "Foreigner", tier3: "renew" },
]

标签: javascriptnode.jsarraysjson

解决方案


维护Set对象中每个键的值。使用map并获取更新后的过滤对象。(更新的对象将是尚未拥有的键)

const all = {};

const updateObject = (obj) =>
  Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => {
      if (!(key in all)) {
        all[key] = new Set();
      }
      const result = !all[key].has(value);
      all[key].add(value);
      return result;
    })
  );

const output = arr => arr.map(updateObject);

data = [
  {
    tier1: "Normal",
    tier2: "none",
    tier3: "none",
    tier4: "none",
    tier5: "none",
  },
  {
    tier1: "Urgent",
    tier2: "GCC & Labour",
    tier3: "new",
    tier4: "Cancellation",
    tier5: "Cancellation",
  },
  {
    tier1: "Urgent",
    tier2: "Foreigner",
    tier3: "renew",
    tier4: "Cancellation",
    tier5: "none",
  },
];



console.log(output(data));


推荐阅读