使用_.each查找数组中的对象

时间:2011-10-12 11:44:40

标签: javascript underscore.js

我有一个看起来像这样的数组 -

     list = [{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "345", "name":"xyz"}},{"doc":{"id": "123", "name":"str"}}]

如何使用_.each方法检索id =“123”的doc对象?任何帮助是极大的赞赏。

干杯!

4 个答案:

答案 0 :(得分:15)

实际上,_.detect更适合解决这个问题:

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"});

结果:

{"doc":{"id": "123", "name":"abc"}}

或者,如果您想要返回id ='123'的两个对象,则可以将_.detect替换为_.select

_.select(list, function (obj) {return obj.doc.id === "123"});

结果:

[{"doc":{"id": "123", "name":"abc"}}, {"doc":{"id": "123", "name":"str"}}]

答案 1 :(得分:5)

阅读jQuery.each如何处理中断;

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);

答案 2 :(得分:0)

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))


})

答案 3 :(得分:0)

因为你有2个id为123的结果我添加了数组结果。如果您有1个结果,则可以返回obj.doc而不是将其添加到结果

var result = [];
$.each(list, function(index, obj) { 
    if(obj.doc.id == 123) {
        result.push(obj.doc);
    }
});