4

I am trying to pull all unique Field names from the returned results of an Ajax call. However, for whatever reason, the Field name DRMrole continues to appear twice.

Here is the jQuery I am using

//Construct array to determine unique Field names
var fieldArray = [];
$.each(data, function(i, item){
    fieldArray.push(item.Field);
    console.log(item.Field);
});
fieldArray = $.unique(fieldArray);
console.log(fieldArray);

And here are the readouts from the console.log commands

enter image description here

As you can see, for some reason DRMrole appears twice in the filtered results. This happens each and every time I run this code so doesn't appear to be random.

4

3 回答 3

14

您始终可以使用对象而不是数组 - 将每个项目作为属性放置在对象中。您尝试插入的每个相同的键都会简单地覆盖现有的键:

var fieldArray = {}; // object instead of array
$.each(data, function(i, item){
    fieldArray[item.Field] = item.Field;
});

这是jsFiddle 上的一个超级简单的例子


另一种选择(如sbeliv01的评论中所述)是使用该函数来测试元素是否已经存在:$.inArray()

var fieldArray = [];
$.each(data, function(i, item){
  if ($.inArray(item.Field,fieldArray) === -1){
    fieldArray.push(item.Field);
  }
});

参考 -$.inArray()

于 2013-05-10T21:44:49.403 回答
1

如果您已经有一个想要“唯一化”的数组,则另一种选择

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}
于 2013-05-10T21:57:25.383 回答
-3

变量 x = [2, 3, 6, 3, 2, 5];

x = x.filter(function(a,b,c){ return c.indexOf(a,- c.length) >= b ? true :false ; });

于 2014-10-28T17:54:33.663 回答