This question already has an answer here:
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?
To get first object from array of objects by a specific property value:
Try Array filter method for filter the
array of objects
withproperty
.using array filter method:
using for in loop :
Working fiddle : https://jsfiddle.net/uq9n9g77/
OK, there are few ways to do that, but let's start with the simplest one and latest approach to do this, this function is called
find()
.Just be careful when you using
find
to as even IE11 dosn't support it, so it needs to be transpiled...so you have this object as you said:
and you can write a function and get it like this:
and use the function like this:
Also in ES6 for even shortened version:
This method only return the first value which match..., for better result and browser support, you can use
filter
:and we will return
[{a: 5, b: 6}]
...This method will return an array instead...
You simpley use for loop as well, create a function like this:
and call it like this:
If I understand correctly, you want to find the object in the array whose
b
property is6
?Or if you were using underscore:
to access the third object, use:
jsObjects[2];
to access the third object b value, use:
jsObjects[2].b;