检查具有索引的对象是否在数组中

时间:2014-10-14 23:26:15

标签: javascript jquery arrays object each

$.each(constructions, function(i,v) { 
if ($.inArray(v.name, map[ii].buildings) == -1) {//stuff}
};

其中constructions是一个对象数组,每个对象都有一个唯一的名称。 map[ii].buildings是一个包含其中一些对象的数组。我想迭代constructions中的每个对象,检查其名称参数是否出现在map[ii].buildings的对象中。

如果map[ii].buildings数组中的每个元素只是对象名称的文本字符串,则上述代码有效,但如果该元素是整个对象,则不起作用.. close,但没有骰子>。<

2 个答案:

答案 0 :(得分:2)

尝试使用$.grep()代替$.inArray();您可以指定一个函数来为您进行过滤。

检查$.grep()返回的数组是否length == 0

,而不是检查-1。

简单的例子:(如果您发布了#34;构造"对象的代码/示例,会更容易)



    var constructions = [{
        Name: "Mess hall",
        SqFt: 5000
    }, {
        Name: "Infirmary",
        SqFt: 2000
    }, {
        Name: "Bungalow",
        SqFt: 2000
    }, {
        Name: "HQ",
        SqFt: 2000
    }];
    
    var buildings = [{
        Name: "Infirmary",
        SqFt: 2000
    }, {
        Name: "HQ",
        SqFt: 2000
    }];
    
    // found buildings will be list of items in "constructions" that is not in "buildings"
    var foundBuildings = $.grep(constructions, function (constructionsItem) {
        return $.grep(buildings, function (buildingsItem) {
            return buildingsItem.Name === constructionsItem.Name
        }).length == 0; // == 0 means "not in", and > 0 means "in"
    });
    
    // this just renders the results all pretty for ya
    $.each(foundBuildings, function (idx, item) {
        $("#output").append("<div>" + item.Name + "</div>");
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
&#13;
&#13;
&#13;

示例jsFiddle:http://jsfiddle.net/eLeuy9eg/3/

答案 1 :(得分:0)

非jQuery这样做的方法是使用filter。像这样:

// pass in an array and the key for which you want values
// it returns an array of those values
function getValues(arr, key) {
  return arr.map(function (el) { return el[key]; });
}

function notFoundIn(arr, arr2) {

  // grab the names of the buildings
  var buildings = getValues(arr2, 'name');

  // grab the names from the construction objects and filter
  // those that are not in the building array
  return getValues(arr, 'name').filter(function (el) {
    return buildings.indexOf(el) === -1;
  });
}

notFoundIn(constructions, buildings); // eg [ "one", "three" ]

DEMO

您甚至可以为数组原型添加新方法。使用这个,您可以使用简单数组或传入键的对象数组。请注意,在此示例中,我已使用执行相同功能的循环替换mapfilter,但速度更快(请参阅注释):

function getValues(arr, key) {
  var out = [];
  for (var i = 0, l = arr.length; i < l; i++) {
    out.push(arr[i][key]);
  }
  return out;
}

if (!Array.prototype.notFoundIn) {
  Array.prototype.notFoundIn = function (inThisArray, key) {
    var thisArr = key ? getValues(this, key) : this;
    var arrIn = key ? getValues(inThisArray, key) : inThisArray;
    var out = [];
    for (var i = 0, l = thisArr.length; i < l; i++) {
      if (arrIn.indexOf(thisArr[i]) === -1) {
        out.push(thisArr[i]);
      }
    }
    return out;
  }
}


constructions.notFoundIn(buildings, 'name');
[1, 2, 3].notFoundIn([2]); // [1, 3]

DEMO