I have an array of JSON objects and I want to find the object with a certain property. I know this may look like a duplicate question, but please continue because I think it's slightly different than the previous questions.
A guy I work with suggested using IndexOf, and that got me thinking. Is there something similar to the $elemMatch feature in mongo? Is there some command that basically says, in pseudo-code, "get me the object with this property from this array"? With the iteration, I feel like the psuedo-code says "look at the first object in this array. If this object has this property, get me this object. If not, look at the second object in this array....."
I understand how to use IndexOf like my friend suggested, but the more I thought about it, I started thinking that the IndexOf method might be fewer lines of code, but doesn't it ultimately have to iterate through the objects in the array to find the index of the one I need? So if I want to do something to the object with this property, and I use the method IndexOf to get the index, I would then refer to the object like myArray[indexFromIndexOfMethod], and then modify it accordingly, correct? So, if javascript is iterating over the array itself to perform the IndexOf method, why don't I just write my own iteration and save a step? Now if the IndexOf method uses a more efficient way of locating the array element than just iterating through and checking each one, then it would make sense for me to use it. Otherwise, it does not make sense to use the IndexOf method if you can achieve the same results with a simple iteration.
indexOf
because you can just write your own iteration and duplicate code that's already been written. – WatercoolindexOf
will save you anything. With it, you don't have to write the loop, it does the loop for you. – JudahindexOf
. But as has been stated, this only works because we're comparing to the exact same object. If you were to search for a different, but identical object, based on an identifying property,indexOf
would fail, but all other cases would work. – Epner