$.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
数组中的每个元素只是对象名称的文本字符串,则以上代码有效,但如果元素是整个对象,则无效..关闭,但没有骰子 >.<
最佳答案
尝试使用 $.grep()
而不是 $.inArray()
;您可以指定一个函数来为您进行过滤。
不是检查 -1,而是检查 $.grep()
返回的数组是否有 length == 0
简单示例:(如果您发布“构造”对象的代码/示例会更容易)
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>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
示例 jsFiddle:http://jsfiddle.net/eLeuy9eg/3/
关于javascript - 检查具有索引的对象是否在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372068/