Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get single object from array using JavaScript functions [duplicate]

Tags:

javascript

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?

like image 607
Michael Avatar asked Jul 20 '16 12:07

Michael


People also ask

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you get a list of duplicate objects in an array of objects with JavaScript?

How do you find duplicate objects in an array? Using the indexOf() method. Using the has() method. Using an object & key value pairs.

Can array have duplicate values JavaScript?

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


1 Answers

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)
like image 83
Nenad Vracar Avatar answered Oct 28 '22 13:10

Nenad Vracar