admin管理员组文章数量:1290013
How to write this script properly so I can match the value on the object.
var objGroup = [
{ "color": "YELLOW", "number": "11,7,44,22" },
{ "color": "BLUE", "number": "8,20,9" },
{ "color": "GREEN", "number": "12,34,55" }
];
objGroup.map(function (groupNum) {
if (groupNum.number== "11") {
alert(groupNum.color);
} else {
return null
}
});
How to write this script properly so I can match the value on the object.
var objGroup = [
{ "color": "YELLOW", "number": "11,7,44,22" },
{ "color": "BLUE", "number": "8,20,9" },
{ "color": "GREEN", "number": "12,34,55" }
];
objGroup.map(function (groupNum) {
if (groupNum.number== "11") {
alert(groupNum.color);
} else {
return null
}
});
Share
Improve this question
edited Sep 13, 2012 at 10:52
Richard Dalton
35.8k6 gold badges74 silver badges92 bronze badges
asked Sep 13, 2012 at 10:26
spicykimchispicykimchi
1,1515 gold badges22 silver badges41 bronze badges
1
- Please, can you describe more detailed what you're trying to do? Your number-property is not an object oder array or number. It is a string containing numbers. And you're not using any jQuery in your code?!? – LeJared Commented Sep 13, 2012 at 10:37
1 Answer
Reset to default 8This will return the object that has a number value that contains the supplied number.
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/rVPu5/
Alternative using newer .filter function which won't be as widely supported:
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/rVPu5/2/
Finally - the jQuery version:
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/rVPu5/3/
本文标签: javascriptjQuery find the match value in the multidimensional arrayobjectStack Overflow
版权声明:本文标题:javascript - jQuery find the match value in the multidimensional arrayobject - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741489537a2381555.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论