11

I have this array of objects:

var frequencies = [{id:124,name:'qqq'}, {id:589,name:'www'}, {id:45,name:'eee'}, {id:567,name:'rrr'}]; 

I need to get an object from the array above by the id value.

For example I need to get the object with id = 45.

I tried this:

var t = frequencies.map(function (obj) { return obj.id==45; }); 

But I didn't get the desired object.

How can I implement it using JavaScript prototype functions?

0

    2 Answers 2

    32

    If your id's are unique you can use find()

    var frequencies = [{"id":124,"name":"qqq"},{"id":589,"name":"www"},{"id":45,"name":"eee"},{"id":567,"name":"rrr"}]; var result = frequencies.find(function(e) { return e.id == 45; }); console.log(result)

    1
    • Great! find() is perfect as it only returns a single entry from an array :-)
      – Philipp
      CommentedMay 24, 2019 at 10:07
    23

    You need filter() not map()

    var t = frequencies.filter(function (obj) { return obj.id==45; })[0]; 
    5
    • Is filter method works in InternetExplorer?
      – Michael
      CommentedJul 20, 2016 at 12:57
    • @Michael: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… .CommentedJul 20, 2016 at 12:58
    • 3
      Filter method return array(a single object array), any idea how can return object not array?
      – Michael
      CommentedJul 20, 2016 at 13:14
    • Yes. As filter will return an array. So you can easily user array[0] to get the product. That means if an array of single object is like singleObjectArray = [{name: "laptop"}]... You can easily extract the object from the array like-- singleObject = singleObjectArray[0];CommentedOct 19, 2022 at 19:30
    • You should use find because it returns the object instead of an array.CommentedFeb 2, 2024 at 13:33

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.