简体   繁体   English

如果属性值匹配,则从数组中删除对象

[英]remove object from array if property value match

I have array of objects that look like: 我有一系列看起来像的对象:

{
  "brandid": id,
  "brand": string,
  "id": id,
  "categoryId": id,
  "category": string,
  "factory": string,
  "series": string,
  "status": 0,
  "subStatus": 1
}

if the series property value matches another series property value in the other objects in the array, that object needs to be removed from the array. 如果series属性值与数组中其他对象中的另一个series属性值匹配,则需要从数组中删除该对象。

Currently I have attempted to push them to a duplicate Array with : 目前,我尝试使用以下命令将它们推送到重复的数组:

      const seriesResCopy = seriesRes;
      const dupArray = []
      for (const thing of seriesResCopy) {
        for (const item of seriesRes) {
          if (thing.series === item.series) {
            dupArray.push(item);
          }
        }
      }

but this does not work. 但这不起作用。 From examples I have seem my issue has been that I do not have a definite list of duplicate values to look for. 从示例看来,我的问题似乎是我没有要查找的重复值的明确列表。

Any help would be much appreciated. 任何帮助将非常感激。

You could use a Set of series to filter out duplicates: 您可以使用一系列序列来过滤出重复项:

const exists = new Set();
seriesRes = seriesRes.filter(({series}) => !exists.has(series) && exists.add(series));

This uses: Array.prototype.filter , Object destructuring and some logical tricks. 它使用: Array.prototype.filter ,对象解构和一些逻辑技巧。

The same can be done by mutating the array: 可以通过更改数组来完成此操作:

const exists = new Set();
for(const [index, {series}] of seriesRes.entries()) {
  if(!exists.has(series) {
    exists.add(series);
  } else {
    seriesRes.splice(index, 1);
  }
}

To filter duplicates from the array and keep the first instance: 要从数组中过滤重复项并保留第一个实例:

let seriesWithoutDuplicates = seriesRes.filter((s, i, self) => {
    return self.findIndex(z => z.series === s.series) === i;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM