如何返回对象数组的非重复值

时间:2016-03-05 07:03:14

标签: javascript

var newarray= 
[ { value: 'Large', name: 'Size' },
{ value: 'Red', name: 'Color' },
{ value: 'Cotton', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' },
{ value: 'Large', name: 'Size' },
{ value: 'Red', name: 'Color' },
{ value: 'Jute', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' },
{ value: 'Large', name: 'Size' },
{ value: 'Green', name: 'Color' },
{ value: 'Jute', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' } ];

这是我的数组我需要在数组中找到具有非重复值的唯一对象数组,请帮忙

2 个答案:

答案 0 :(得分:1)

如果项目存储在哈希映射中,我建议迭代数组并过滤项目。



var array = [{ value: 'Large', name: 'Size' }, { value: 'Red', name: 'Color' }, { value: 'Cotton', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }, { value: 'Large', name: 'Size' }, { value: 'Red', name: 'Color' }, { value: 'Jute', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }, { value: 'Large', name: 'Size' }, { value: 'Green', name: 'Color' }, { value: 'Jute', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }],
    unique = function (a) {
        var o = {};
        return a.filter(function (b) {
            var k = b.name + '|' + b.value;
            if (!(k in o)) {
                o[k] = true;
                return true;
            }
        });
    }(array);

document.write('<pre>' + JSON.stringify(unique, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用Set获取唯一值

var uniq = Array.from(new Set(newarray.map(function(a) {
    return JSON.stringify(a);
}))).map(function(a) {
    return JSON.parse(a)
});

console.log(uniq); // will print your unique values