Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JavaScript object from array of objects by value of property [duplicate]

Let's say I have an array of four objects:

var jsObjects = [    {a: 1, b: 2},     {a: 3, b: 4},     {a: 5, b: 6},     {a: 7, b: 8} ]; 

Is there a way that I can get the third object ({a: 5, b: 6}) by the value of the property b for example without a for...in loop?

like image 725
user765368 Avatar asked Dec 20 '12 01:12

user765368


People also ask

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

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.

How can I check if the array of objects have duplicate property values?

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.


1 Answers

Filter array of objects, which property matches value, returns array:

var result = jsObjects.filter(obj => {   return obj.b === 6 }) 

See the MDN Docs on Array.prototype.filter()

const jsObjects = [    {a: 1, b: 2},     {a: 3, b: 4},     {a: 5, b: 6},     {a: 7, b: 8}  ]    let result = jsObjects.filter(obj => {    return obj.b === 6  })    console.log(result)

Find the value of the first element/object in the array, otherwise undefined is returned.

var result = jsObjects.find(obj => {   return obj.b === 6 }) 

See the MDN Docs on Array.prototype.find()

const jsObjects = [    {a: 1, b: 2},     {a: 3, b: 4},     {a: 5, b: 6},     {a: 7, b: 8}  ]    let result = jsObjects.find(obj => {    return obj.b === 6  })    console.log(result)
like image 93
elclanrs Avatar answered Oct 18 '22 20:10

elclanrs