json 从任何数组中筛选唯一对象[重复]

zrfyljdw  于 2023-04-08  发布在  其他
关注(0)|答案(2)|浏览(136)

此问题已在此处有答案

javascript - find unique objects in array based on multiple properties(9个回答)
昨天关门了。
我在javascript中有一个对象数组,我正在从它创建一个新数组,但只有一些属性。我需要的是过滤唯一的对象并消除重复的对象,我试图在相同的函数中做到这一点,但我不知道是否可能
这就是数组:

let filters = [
  {
     "model":"audi",
     "year":2012,
     "country":"spain"
  },
  {
    "model":"bmw",
    "year":2013,
    "country":"italy"
  },
  {
    "model":"audi",
    "year":2020,
    "country":"spain"
  }
]

这是一个函数:

function filterObject(data: any) {
  let result = data.map((item: any) => {
    return {
      hub: {
        country: item.country,
        model: item.model
      }
    }
  })
  return result

}

这是我得到的:

[
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   },
   {
      "hub":{
         "country":"italy",
         "model":"bmw"
      }
   },
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   }
]

这就是我需要的:

[
   {
      "hub":{
         "country":"spain",
         "model":"audi"
      }
   },
   {
      "hub":{
         "country":"italy",
         "model":"bmw"
      }
   }
]
djmepvbi

djmepvbi1#

试试这个更新的功能

function filterObject(data: any) {
  let hubs: {[key: string]: any} = {};

  data.forEach((item: any) => {
    const key = `${item.country}-${item.model}`;

    if (!hubs[key] || item.year > hubs[key].year) {
      hubs[key] = { country: item.country, model: item.model, year: item.year };
    }
  });

  let result = Object.values(hubs).map((hub) => {
    return { hub: { country: hub.country, model: hub.model } };
  });

  return result;
}

按照你的期望工作。

nzk0hqpo

nzk0hqpo2#

您可以使用Map来确保只有唯一的项目:

function filterObject(data:any) {
  const uniqueObjects:any = [];
  const uniqueMap = new Map();

  data.forEach((item:any) => {
    const key = item.model + item.country;
    if (!uniqueMap.has(key)) {
      uniqueMap.set(key, true);
      uniqueObjects.push({
        hub: {
          country: item.country,
          model: item.model
        }
      });
    }
  });

  return uniqueObjects;
}

Playground

相关问题