0

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!

1
  • 1
    _.each is from Underscore.js, not from jQuery... Commented Oct 12, 2011 at 11:49

4 Answers 4

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"}}]
Sign up to request clarification or add additional context in comments.

2 Comments

Great answer! Does the job perfectly!
What if you wanted the index instead of the object returned?
5

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

Comments

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


})

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.