0

I'm looking for the index of an item in an array of a list of objects by looking for a specific value inside of an object

currently, I'm doing this via

var x = [{ _id: '59974d9015a07e09b88e3b53', status: '1', id: '59974d2915a07e09b88e3b4b' }, { _id: '12345', status: '1', id: '54321' }]
var index = null;
for (var i=0; i<x.length; i++) {
 if ( x[i]._id == '59974d9015a07e09b88e3b53' ) {
 index = i;
 break;
 }
}

https://jsfiddle.net/yaocpsjd/

is there a more elegant solution via ES* where I wouldn't need to do a loop?

asked Sep 24, 2017 at 11:57

1 Answer 1

1

You can use findIndex() method that returns index of first element that satisfies condition otherwise it returns -1.

var x = [{
 _id: '59974d9015a07e09b88e3b53',
 status: '1',
 id: '59974d2915a07e09b88e3b4b'
}, {
 _id: '12345',
 status: '1',
 id: '54321'
}]
var index = x.findIndex(e => e._id == '59974d9015a07e09b88e3b53')
console.log(index)

answered Sep 24, 2017 at 11:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.