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)

Sign up to request clarification or add additional context in comments.

1 Comment

Great! find() is perfect as it only returns a single entry from an array :-)
23

You need filter() not map()

var t = frequencies.filter(function (obj) { 
    return obj.id==45; 
})[0];

5 Comments

Is filter method works in InternetExplorer?
Filter method return array(a single object array), any idea how can return object not array?
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];
You should use find because it returns the object instead of an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.