根据属性

时间:2017-10-02 14:00:31

标签: javascript angularjs arrays

我想基于对象属性创建一个没有重复对象的数组(所有对象都是唯一的),如果它是唯一的,我想将它推送到这个数组。 在将其发送到我的功能之前,我使用:

vm.initResponse = angular.fromJson(response);

$$hashKey推送到每个对象。

    function initDropDown(list){
        console.log('initDropDown', list);
        for (var key in list) {
            //remove angularjs $$hashKey
            var obj = JSON.parse(angular.toJson(list[key]));
            //the object I want to push into new array
            var filter = {};
            filter.prop = obj.SUGNIA;
            //if indexOf returns -1 the array does not have this object
            if(vm.stockOptionsSelect.indexOf(filter) < 0){
                vm.stockOptionsSelect.push(filter);
            }

        }
    }

list数组有许多不同SUGNIA的对象,我想创建一个包含所有唯一对象的数组。

我已移除$$hashKey已解释remove-hashKey并使用indexOf - indexOf

列出数据 -

[
  {
    "uid": "23",
    "time": "2017-10-01 16:00:35.515",
    "SUGNIA": "stock",
    "SECURITYNAME": "IBM",
    "INDEX_IN_UI": 5
  },
  {
    "uid": "29",
    "SECURITYNUM": 629014,
    "time": "2017-09-28 16:32:26.432",
    "SUGNIA": "holdings",
    "SECURITYNAME": "FaceBook",

    "INDEX_IN_UI": 10
  },
  {
    "uid": "id",
    "time": "2017-09-28 16:33:20.25",
    "SUGNIA": "stock",
    "SECURITYNAME": "google",
    "INDEX_IN_UI": 0
  }
]

我的结果应该是:

[{"prop":"stock"}, {"prop":"holding"}]

但我得到重复。

3 个答案:

答案 0 :(得分:2)

indexOf函数使用严格相等===进行比较,并且由于您传递给此函数的对象是刚刚创建的对象,因此它将始终返回-1

要解决此问题,您可以改为使用...some(...)功能。

以下是一个例子:

if(!vm.stockOptionsSelect.some(e => e.prop == obj.SUGNIA)){
    vm.stockOptionsSelect.push({prop:obj.SUGNIA});
}

答案 1 :(得分:1)

您不能使用indexof对象,因为它不会查看对象属性,但它正在寻找对该过滤器对象的引用。请改用一些并查找相同的对象属性。

var hasItem = vm.stockOptionsSelect.some(item) {
    return item.prop === filter.prop
}
if(!hasItem) {
    vm.stockOptionsSelect.push(filter);
}

如果你不能使用某些

var results = vm.stockOptionsSelect.filter(item) {
    return item.prop === filter.prop;
}
if(results.length === 0) {
    vm.stockOptionsSelect.push(filter);
}

答案 2 :(得分:1)

您可以使用Setarray#map来获取数组SUGNIA中唯一的list值。

&#13;
&#13;
var list = [{"uid": "23","time": "2017-10-01 16:00:35.515","SUGNIA": "stock","SECURITYNAME": "IBM","INDEX_IN_UI": 5},{"uid": "29","SECURITYNUM": 629014,"time": "2017-09-28 16:32:26.432","SUGNIA": "holdings","SECURITYNAME": "FaceBook","INDEX_IN_UI": 10},{"uid": "id","time": "2017-09-28 16:33:20.25","SUGNIA": "stock","SECURITYNAME": "google","INDEX_IN_UI": 0}];

var result = [...new Set(list.map(x => x.SUGNIA))]
             .map(x => ({prop: x}));
             
console.log(result);
&#13;
&#13;
&#13;