获取JSON的唯一对象

时间:2015-11-05 07:53:10

标签: json angularjs lodash

我有这种阵列:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

我想过滤它:

var bar = [ { "a" : "1" }, { "b" : "2" }];

这是我的plunker

plunker的第7行,当我写return JSON.stringify( x );时它很好但是返回字符串JSON ..但是当我写return x;时它变坏了并且不返回Unique JSON。

3 个答案:

答案 0 :(得分:2)

您只需使用 var jsonObjdata = []; var yearExist = ""; var weekExist = ""; var SampleRequestBody = {}; $.each(data, function (key, value) { if (value.year != yearExist) { SampleRequestBody.week = value.week; SampleRequestBody.firstYear = value.changes; yearExist = value.year; } else if (value.year == yearExist && value.week == weekExist + 1) { SampleRequestBody.secondYear = value.changes; } else if (value.year == yearExist && value.week == weekExist + 1) { SampleRequestBody.thildYear = value.changes; jsonObjdata.push(SampleRequestBody); } }); 即可,无需收集:

uniq

此处更新了plunk:http://plnkr.co/edit/KYW6UybdiBxuvOVX8naP?p=preview

答案 1 :(得分:1)

first you can download underscorejs then you can use the following code

 var foo = [{ "a": "1" }, { "b": "2" }, { "a": "1" }];
            var result = _.uniq(foo, function (obj) {
                return JSON.stringify(obj);
            });


 refere the following url  http://underscorejs.org/

答案 2 :(得分:0)

您可以使用var uniqueList =_.uniq(foo, 'a');以下是doc:https://lodash.com/docs#uniq 这里是plunker:http://plnkr.co/edit/HkirGPrs3dGZMUEnEKiT?p=preview