Check if object key exists within object

后端 未结 7 1785
终归单人心
终归单人心 2020-12-31 04:16

I\'m trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new

7条回答
  •  隐瞒了意图╮
    2020-12-31 05:11

    ExampleArray

    [0] => siteoverlay
    [1] => overlaycenter
    [2] => someelementid
    

    Solution A

    extend prototype if you want,(function here with while loop which is much faster than for in):

    if (!('getKey' in Object.prototype)) {
            Object.prototype.getKey = function(obj) {
            var i=this.length; 
                while(i--)
                {  if(this[i]===obj)
                      {return i;} 
                       return;
                }
           };
    }
    

    then you can use:

    alert(exampleArray.getKey("overlaycenter"));  
    

    returns: 1

    Solution B

    also with prototype extension:

    if(!('array_flip' in Array.prototype)){
          Array.prototype.array_flip=function(array) {
            tmp_ar={}; var i = this.length;
            while(i--)
            {   if ( this.hasOwnProperty( i ) )
                   { tmp_ar[this[i]]=i; }
            } return tmp_ar;    
          };
      }
    

    and then you can use:

    alert(exampleArray.array_flip(exampleArray['someelementid']);
    

    returns: 2

    Solution C

    found out without prototype addition it is also functional

    and eventually better for compatible scripting as everyone says not to extend the prototype...and so,...yes, if you want to use it with an easy 1 liner then you can use:

        function array_flip( array )
        {  tmp_ar={};  var i = array.length;
            while(i--)
            {  if ( array.hasOwnProperty( i ) )
                  { tmp_ar[array[i]]=i; }
            } return tmp_ar;    
        }
    

    And

    alert(array_flip(exampleArray)['siteoverlay']);
    

    returns 0

提交回复
热议问题