这将返回具有包含所提供数字的数字值的对象。
var objGroup = [
{ "color": "YELLOW", "number": "11,7,44,22" },
{ "color": "BLUE", "number": "8,20,9" },
{ "color": "GREEN", "number": "12,34,55" }
];
var found = findItem(objGroup, '11');
function findItem(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i].number.split(',').indexOf(value) >= 0) {
return objGroup[i];
}
}
}
if (found) {
alert(found.color);
}
http://jsfiddle.net/rVPu5/
替代使用较新的 .filter 函数,该函数不会被广泛支持:
var found = objGroup.filter(function(item) {
if (item.number.split(',').indexOf('11') >= 0) {
return true;
}
return false;
});
if (found.length > 0) {
alert(found[0].color);
}
http://jsfiddle.net/rVPu5/2/
最后 - jQuery 版本:
var found = $.map(objGroup, function(item) {
if (item.number.split(',').indexOf('11') >= 0) {
return item;
}
});
if (found.length > 0) {
alert(found[0].color);
}
http://jsfiddle.net/rVPu5/3/