verdure
verdure

Reputation: 3341

using _.each to find object in an array

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!

Upvotes: 0

Views: 9525

Answers (4)

Martin Ogden
Martin Ogden

Reputation: 882

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"}}]

Upvotes: 15

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

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

Upvotes: 0

erimerturk
erimerturk

Reputation: 4288

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


})

Upvotes: 0

rodneyrehm
rodneyrehm

Reputation: 13557

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

Upvotes: 5

Related Questions