10

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Michael
  • 13,950
  • 57
  • 145
  • 288

2 Answers2

31

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
22

You need filter() not map()

var t = frequencies.filter(function (obj) { 
    return obj.id==45; 
})[0];
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Is filter method works in InternetExplorer? – Michael Jul 20 '16 at 12:57
  • @Michael: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility . – Felix Kling Jul 20 '16 at 12:58
  • 3
    Filter method return array(a single object array), any idea how can return object not array? – Michael Jul 20 '16 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]; – Asif Ur Rahman Oct 19 '22 at 19:30