0

How do I determine what the index of an object is within an array?

Take the following setup:

var item = [
 {
 identifier: "id1",
 },
 {
 identifier: "id2",
 },
 {
 identifier: "id3",
 }
];

I know what the object value is and that it exists and currrently have it stored like this currentValue = "id2";

What i'd like to know is that "id2" equals to (in this case) index 1.

JAAulde
19.5k5 gold badges56 silver badges65 bronze badges
asked Mar 21, 2015 at 22:43

1 Answer 1

1

The only way is to iterate and check each property

var currentValue = "id2";
var item = [
 {
 identifier: "id1",
 },
 {
 identifier: "id2",
 },
 {
 identifier: "id3",
 }
];
var index = 0;
item.forEach(function(obj, i) {
 if ( obj.identifier === currentValue ) {
 index = i;
 return false;
 }
});
document.body.innerHTML = index;

answered Mar 21, 2015 at 22:45
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.