admin管理员组文章数量:1221478
I have an array which looks looks like this -
list = [{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "345", "name":"xyz"}},{"doc":{"id": "123", "name":"str"}}]
How can I use the _.each method to retrieve the doc object with id ="123" ? Any help is greatly appreciated.
Cheers!
I have an array which looks looks like this -
list = [{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "345", "name":"xyz"}},{"doc":{"id": "123", "name":"str"}}]
How can I use the _.each method to retrieve the doc object with id ="123" ? Any help is greatly appreciated.
Cheers!
Share Improve this question edited Oct 12, 2011 at 11:49 verdure asked Oct 12, 2011 at 11:44 verdureverdure 3,3416 gold badges27 silver badges27 bronze badges 1 |4 Answers
Reset to default 15Actually, _.detect would be more a appropriate function to solve this problem:
var list = [
{"doc":{"id": "123", "name":"abc"}},
{"doc":{"id": "345", "name":"xyz"}},
{"doc":{"id": "123", "name":"str"}}
];
_.detect(list, function (obj) {return obj.doc.id === "123"});
result:
{"doc":{"id": "123", "name":"abc"}}
Alternatively, if you'd like to return both objects with id = '123', then you could substitute _.detect with _.select.
_.select(list, function (obj) {return obj.doc.id === "123"});
result:
[{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "123", "name":"str"}}]
Read up on how jQuery.each handles break;
var object_with_id_123;
$.each(list, function(key, val){
if (val.doc.id == "123") {
object_with_id_123 = val;
return false; // break;
}
return true; // continue; - just to satisfy jsLint
});
console.log(object_with_id_123);
var list = [{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "345", "name":"xyz"}},{"doc":{"id": "123", "name":"str"}}]
var olist = [];
$.each(list,function(key, value){
if(value.doc.id =="123"){
olist.push(value);
}
})
$.each(olist,function(key, value){
alert(JSON.stringify(value))
})
because you have 2 results with id 123 i've added the array result. If you have 1 result, you could return obj.doc instead of adding it to result
var result = [];
$.each(list, function(index, obj) {
if(obj.doc.id == 123) {
result.push(obj.doc);
}
});
本文标签: javascriptusing each to find object in an arrayStack Overflow
版权声明:本文标题:javascript - using _.each to find object in an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739347989a2159250.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
_.each
is from Underscore.js, not from jQuery... – ThiefMaster Commented Oct 12, 2011 at 11:49