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

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

问题描述

我有一个对象数组,我想根据特定的键:值对来减少这些对象。我想创建一个数组,每个特定的键只包含一个对象: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.

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

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.


推荐答案

您可以使用下划线

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

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

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

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