2014-09-26 69 views
0

使用jQuery,我只想从对象数组中只输出一次相同的值。我想我可以创建一个临时数组,并在我迭代对象时进行比较,但不太清楚如何去做。只从对象数组中输出一次相同的值

物体看起来像这样,

[{"type":"Sample1","manufacturer":"Sample2","model":"Sample3"},{"type":"Sample1","manufacturer":"Sample4","model":"Sample5"}] 

说我只希望输出类型样本1次,

所有的
var sampleObject, 
    storage = []; 

$.each(sampleObject, function(key, item) { 
    if (!$.inArray(storage.item == item)) { 
     console.log(item); 
     storage.push(item); 
    } 
}); 
+0

你给到'存储什么样的价值'? – Stryner 2014-09-26 14:11:44

+0

很抱歉忘记了包含零件,查看更新。 – 2014-09-26 14:13:28

回答

0

意识到我可能只是不喜欢这样,而不是避免比较阵列的麻烦,

var type, 
     brand, 
     model; 

    $.each(data, function (key, item) { 
     if (item['type'] != type) { 
      // Output type 
     } 
     if (item['manufacturer'] != brand) { 
      // Output brand 
     } 
     if (item['model'] != model) { 
      // Output model 
     } 

     type = item['type']; 
     brand = item['manufacturer']; 
     model = item['model']; 
    }); 
1

首先,您使用的inArray错误。从jQuery文档:

jQuery.inArray(value, array [, fromIndex ]) 

它返回位置(索引)在数组中找到值。

if (!$.inArray(storage.item == item)) 

没有意义。它应该是:

if ($.inArray(item, storage.item)==-1) 

但是,那么比较是错误的。您应该迭代项目中的每个值并将每个值存储在存储阵列中。

检查,如果这是你想要什么:

$.each(sampleObject, function(key, item) { 
    var found = false; 
    $.each(item, function (prop, val) { 
    if($.inArray(val, storage) == -1){ 
     storage.push(val); 
    } else { 
     found = true; 
    } 
    }); 
    if (!found) 
    console.log(item) 
}); 
+0

谢谢阿米特。我采取了另一种方法,并意识到它可以用更简单的方式解决,因为我不需要比较数组,请参阅更新后的帖子。 – 2014-09-26 16:07:16

相关问题