【问题标题】:Only output same value once from object array仅从对象数组中输出一次相同的值
【发布时间】:2014-09-26 14:08:06
【问题描述】:

使用 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);
    }
});

【问题讨论】:

  • 你给storage什么价值?
  • 抱歉忘记包含部分,请参阅更新。

标签: jquery arrays loops object compare


【解决方案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)
});

【讨论】:

  • 谢谢阿米特。我采用了另一种方法,并意识到它可以用更简单的方式解决,因为我真的不需要比较数组,请参阅更新后的帖子。
【解决方案2】:

意识到我可以这样做,避免比较数组的麻烦,

    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'];
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 2017-03-12
    • 2020-06-27
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多