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
  • 1 _.each is from Underscore.js, not from jQuery... – ThiefMaster Commented Oct 12, 2011 at 11:49
Add a comment  | 

4 Answers 4

Reset to default 15

Actually, _.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