1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sat
  • 40,138
  • 28
  • 93
  • 102
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Heretic Monkey Jul 01 '22 at 23:54

2 Answers2

3

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;
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • yep , that way I understand. I thought if there is some inbuilt functions to do the search , like we can sort an array depending on the objects property using array.sort() and compare function. – sat Sep 02 '10 at 07:56
  • @sat: Not really. These are the methods available for Arrays: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array. In JavaScript 1.6 there is the `filter()` method, but that would still be too complex for your requirement. – Daniel Vassallo Sep 02 '10 at 08:07
0

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
    ref: Implementing Mozilla's toSource() method in Internet Explorer

  • what if there are monsters with strings containing:
    1. ,'s . . . as in . . . [",,or",,{p:"1,2,3,"}]
    2. {x:...} or {"x":...} . . . as in . . . ['{"x":...}'," and ","{x:...}",,]
      (which will screw up the above coding using either JSON or toSource)
    3. nested monsters
    4. other monstrosities are mere chimeras ... not paid enough to do or prove
Community
  • 1
  • 1
Ekim
  • 353
  • 2
  • 4