使用jQuery,我想只从对象数组输出一次相同的值。我想我可以创建一个临时数组,并在迭代对象时进行比较,但不太确定如何进行。
对象看起来像这样,
[{"type":"Sample1","manufacturer":"Sample2","model":"Sample3"},{"type":"Sample1","manufacturer":"Sample4","model":"Sample5"}]
假设我只想输出一次类型Sample1,
var sampleObject,
storage = [];
$.each( sampleObject, function( key, item ) {
if (!$.inArray(storage.item == item)) {
console.log(item);
storage.push(item);
}
});
答案 0 :(得分:1)
首先,您使用inArray是错误的。来自jQuery文档:
jQuery.inArray( value, array [, fromIndex ] )
它返回在数组中找到值的位置(索引)。
if (!$.inArray(storage.item == item))
没有意义。它应该是:
if ($.inArray(item, storage.item)==-1)
但是,那么比较也是错误的。您应该迭代item中的每个值并将每个值放入存储数组中。
检查这是否是您想要的:
$.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)
});
答案 1 :(得分: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'];
});