JavaScript:删除共享相同属性值的对象的重复项 [英] JavaScript: Remove duplicates of objects sharing same property value

查看:24
本文介绍了JavaScript:删除共享相同属性值的对象的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想根据特定的 key:value 对修剪这些对象.我想创建一个数组,其中每个特定的 key:value 对只包含一个对象.将重复项中的哪个对象复制到新数组中并不重要.

I have an array of objects that I would like to trim down based on a specific key:value pair. I want to create an array that includes only one object per this specific key:value pair. It doesn't necessarily matter which object of the duplicates is copied to the new array.

例如,我想根据 arrayWithDuplicatesprice 属性进行修剪,创建一个仅包含每个值之一的新数组:

For example, I want to trim based on the price property of arrayWithDuplicates, creating a new array that only includes one of each value:

var arrayWithDuplicates = [
  {"color":"red", 
    "size": "small",
    "custom": {
      "inStock": true,
      "price": 10
    }
  },
  {"color":"green", 
    "size": "small",
    "custom": {
      "inStock": true,
      "price": 30
    }
  },
  {"color":"blue", 
    "size": "medium",
    "custom": {
      "inStock": true,
      "price": 30
    }
  },
  {"color":"red", 
    "size": "large",
    "custom": {
      "inStock": true,
      "price": 20
    }
  }
];

会变成:

var trimmedArray = [
  {"color":"red", 
    "size": "small",
    "custom": {
      "inStock": true,
      "price": 10
    }
  },
  {"color":"green", 
    "size": "small",
    "custom": {
      "inStock": true,
      "price": 30
    }
  },
  {"color":"red", 
    "size": "large",
    "custom": {
      "inStock": true,
      "price": 20
    }
  }
];

是否有 JavaScript 或 Angular 函数可以循环执行此操作?

Is there a JavaScript or Angular function that would loop through and do this?

要过滤的属性嵌套在另一个属性中.

The property to filter on is nested within another property.

推荐答案

您可以使用 underscore 来解决这个问题:

You can use underscore for this:

//by size:
var uSize = _.uniqBy(arrayWithDuplicates, function(p){ return p.size; });

//by custom.price;
var uPrice = _.uniqBy(arrayWithDuplicates, function(p){ return p.custom.price; });

这篇关于JavaScript:删除共享相同属性值的对象的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆