Reputation: 41076
How do I search for the property of an object in an array without using for
loops in JavaScript?
If the array is a simple one I can use array.indexOf(value)
to get the index, but what if the array is an array of objects? Other than looping any other way?
For example, ar = [{x,y},{p,q},{u,v}]
. If searched for v
, it should return the array index as 2.
Upvotes: 1
Views: 649
Reputation: 353
Searching for objects in JavaScript arrays
javascript:
/* quick fix naive short solution to be posted soon */
/* array of objects with primitive property values only and no wrinkles */
.
javascript:
alert(
JSON.stringify(
[{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}]
) . match(/"x":/g)
)
and
javascript: /* Does the need to fortify this code imply JSON is stronger? */
alert( /* See wrinkles below */
[{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}] . toSource() .
/*
match(/({|,)\s*x:/g) . join() . replace(/({|,)\s*x:/g,"x:")
finds `x:,x:,x:`
*/
replace(/(({|,)\s*)([^,{:]*):/g,'$1"$3":') . match(/"x":/g)
)
find "x":,"x":,"x":
.
Specific property found, done deal?
Hint, hint (but must be appropriately attenuated and amputated for nested animals):
javascript:
alert(
JSON.stringify([{x:1,y:2},{p:"q"},{u:{},v:[],x:{y:{},x:5}}]) .
match(/"[^"]*":/g)
)
finds "x":,"y":,"p":,"u":,"v":,"x":,"y":,"x":
(all properties - Done Now?)
More (a lot more) brain strain pain will find x:
values and index of array positions (Hint count top level ,
's).
Amputate and attenuate hint (only removes nested array and object ,
's, see wrinkles):
javascript:debug=false;
animal=[
{x:1,y:2},,,{p:"q"},
[ {u:{},vx:[,,], x:{y:{xx:''},x:5} }, "hmmm comma x colon \" monster" ],
];
animal=animal.toSource().replace(/\[(.*)]/,"$1");
/* */ if(debug){
alert(animal);
animal=animal.replace(/\[([^[\]]*)\]/g,
function(a,b,c,d){alert([a,b,c,d].join("\n\n"));return a});
while(animal.search(/\{.*\}|\[.*\]/)>-1){
animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g,
function(a,b,c,d){alert([a,"\n",b,"\n",c]);return b.replace(/,/g,";")});
alert(animal); }
/* */ }
/* the while loops on nesting depth not top array length */
while(animal.search(/\{.*\}|\[.*\]/)>-1)
animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g, /* implicit g loop */
function(a,b,c,d){return (b+c).replace(/,/g," ")}); /* ditto */
alert(animal); /* as opposed to a non-lert animal? */
Wrinkles:
.toSource()
IS stronger (but ... see above) and handles more situations than JSON
,
's . . . as in . . . [",,or",,{p:"1,2,3,"}]
{x:...}
or {"x":...}
. . . as in . . . ['{"x":...}'," and ","{x:...}",,]
JSON
or toSource
)Upvotes: 0
Reputation: 344291
Searching for a value in an array typically requires a sequential search, which requires you to loop over each item until you find a match.
function search(ar, value) {
var i, j;
for (i = 0; i < ar.length; i++) {
for (j in ar[i]) {
if (ar[i][j] === value) return i;
}
}
}
search([{'x': 'y'}, {'p': 'q'}, {'u': 'v'}], 'v'); // returns 2;
Upvotes: 3