search in array of objects
-
Is there a way too search an object property in an array more easily than:
var objArray = [{"nb": 5}, {"nb": 9}]; var isHere = false; for (o in objArray) { if (o.nb == 5) { isHere = true; break; } }
thinking to something more straightforward like:
var objArray = [{"nb": 5}, {"nb": 9}]; var isHere = objArray.contains("nb" == 5);
Which of course makes no sense as it is...
I can evidently write a function but I wonder if a one-liner could exist?
-
Loop is the only way. You can reduce the lines a bit though I think. I'm off for dinner but I'll take a look when I'm back.
-
@d-healey
Something like this could do...var objArray = [{"nb": 5}, {"nb": 9}]; var isHere = false; for (o in objArray) if (isHere = o.nb == 5) break;
-
@ustk Yeah I think that looks pretty good.
-
I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
]; -
Just to make things a bit clearer, Here you have an array with objects, but it does not contains array with named objects... It contains "objects" with "properties".
To get only the object where the property "name" is equal to "string 1":var objectToCopy; for (obj in array) { if (obj.name == "string 1") objectToCopy = obj; }