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?
If you are looking for a single result, rather than an array, may I suggest reduce?
Here is a solution in plain 'ole javascript that returns a matching object if one exists, or null if not.
See this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Example :
Using underscore.js:
It looks like in the ECMAScript 6 proposal there are the
Array
methodsfind()
andfindIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.find()
:findIndex()
:Using find with bind to pass specific key values to a callback function.
I don't know why you are against a for loop (presumably you meant a for loop, not specifically for..in), they are fast and easy to read. Anyhow, here's some options.
For loop:
.filter
.forEach
If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check. e.g.