Searching for objects in JavaScript arrays

后端 未结 2 838
予麋鹿
予麋鹿 2020-12-20 06:17

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.ind

相关标签:
2条回答
  • 2020-12-20 06:39

    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;
    
    0 讨论(0)
  • 2020-12-20 06:53

    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
    0 讨论(0)
提交回复
热议问题