一尘不染

JavaScript:删除具有相同属性值的对象的重复项

angularjs

我有一个对象数组,希望根据特定的对象key:value对进行修剪。我想创建一个数组,此特定key:value对仅包含一个对象。将重复项的哪个对象复制到新数组并不重要。

例如,我要基于的price属性进行修整arrayWithDuplicates,创建一个仅包含每个值之一的新数组:

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函数?

编辑:要筛选的属性嵌套在另一个属性中。


阅读 205

收藏
2020-07-04

共1个答案

一尘不染

您可以为此使用下划线

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

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