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.

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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.