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
  • 756,363
  • 169
  • 1,062
  • 1,111
Michael
  • 12,788
  • 49
  • 133
  • 253

2 Answers2

24

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
  • 111,264
  • 15
  • 131
  • 153
19

You need filter() not map()

var t = frequencies.filter(function (obj) { 
    return obj.id==45; 
})[0];
Satpal
  • 129,808
  • 12
  • 152
  • 166