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
user1231561
3,3698 gold badges41 silver badges57 bronze badges
1 Answer 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
adeneo
319k29 gold badges410 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js