Javasccript Find Element In Array Of Object
Let's say I have an array of objects and one of the properties of each object is TheID. Something like this: TheArray[0].TheID = 34; TheArray[1].TheID = 2352; ... I'm looking to r
Solution 1:
You could use break
to leave the loop:
var TheIndex;
for (var i = 0; i < TheArray.length; i++) {
if (TheArray[i].TheID == MagicNumber) {
TheIndex = i;
break;
}
}
return TheIndex;
Solution 2:
if (TheArray[i].TheID = MagicNumber) { return i; }
Solution 3:
Break;
or return;
within a loop to stop it once you have found what you are looking for. There is no other way to search arrays/objects for specific property values. You could consider re factoring your code entirely to avoid unnecessary performance sinks like this but that isn't always feasible.
Solution 4:
Even though this is from a while ago, another alternative that might be useful if you do many such searches would be to loop once an index based on your search criteria.
e.g. do this once:
var idToIdx={};
for (var i = 0; i < TheArray.length; i++) {
idToIdx['I'+TheArray[i].TheID] = i
}
}
and then just use for idToIdx['I'+ MagicNumber]
as many times as you need.
Post a Comment for "Javasccript Find Element In Array Of Object"