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?
will be better, using return in filter sometimes you can't get result (I dunno why)
How about using
_.find(collection, [predicate=_.identity], [fromIndex=0])
of lo-dash to get object from array of objects by object property value. You could do something like this:Arguments:
Returns
In terms of performance,
_.find()
is faster as it only pulls the first object with property{'b': 6}
, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using_.filter()
method. So in your case, as your array has a single object with this property, I would use_.find()
.Just improved the fastest/best part of this answer to be more re-usable/clear:
From MDN:
Side note: methods like
find()
and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel.You can use it with the arrow function as well like as below :
Filter
array of objects, which property matches value, returns array:See the MDN Docs on Array.prototype.filter()
Find
the value of the first element/object in the array, otherwiseundefined
is returned.See the MDN Docs on Array.prototype.find()