简体   繁体   中英

Check if object key exists within object

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 one, or append data to an existing one.

I've found a few similar questions but none of the answers worked so I'm a bit stuck. It always ends up finding it doesn't exist and creating duplicate keys.

I have the following code, where xxx is where I need to check if the key exists:

var groups = [];    

for (var i=0; i<something.length; i++) {

    var group_key = 'group_'+something[i].group_id;

    if (xxx) {

        // New group

        var group_details = {};

        group_details[group_key] = {
                group_name: something[i].group_name,
                items:  [
                    { 'name': something[i].name }
                ]
        };
        groups.push(group_details);

    } else {

        // Existing group

        groups[group_key].items.push({
            'name': something[i].name
        });

    }

}

The something I am passing in, is pretty simple, basically in the form of:

[
    {
        group_id: 3,
        group_name: 'Group 3',
        name: 'Cat'
    },
    {
        group_id: 3,
        group_name: 'Group 3',
        name: 'Horse'
    },
    {
        group_id: 5,
        group_name: 'Group 5',
        name: 'Orange'
    }
]

The best way to achieve this would be to rely on the fact that the in operator returns a boolean value that indicates if the key is present in the object.

var o = {k: 0};

console.log('k' in o); //true

But this isin't your only issue, you do not have any lookup object that allows you to check if the key is already present or not. Instead of using an array, use a plain object.

var groups = {};

Then instead of groups.push(...) , do groups[group_key] = group_details;

Then you can check if the group exist by doing if (group_key in groups) {}

I have run into this pattern a lot, and what I end up doing is:

if (object[key]) {
    //exists
} else {
    // Does not exist
}

so I think in your case it will be:

if (groups[group_key]) {
    // Exists
} else {
    // Does not exist 
}

 let data = {key: 'John'}; console.log( data.hasOwnProperty('key') );

You should use the in operator

key in object     //true
!(key in object)  //false

And undefined can not be used

obj["key"] !== undefined //false, but the key in the object

For more information, please look at Checking if a key exists in a JavaScript object?

You can use hasOwnProperty() function.

var groups = [];    

for (var i=0; i<something.length; i++) {

    var group_key = 'group_'+something[i].group_id;

    if (!groups.hasOwnProperty(group_key)) {

        // New group

        var group_details = {};

        group_details[group_key] = {//maybe change to group_details =
                group_name: something[i].group_name,
                items:  [
                    { 'name': something[i].name }
                ]
        };

        //groups.push(group_details);
        //change it to
        groups[group_key] = group_details;

    } else {

        // Existing group

        groups[group_key].items.push({
            'name': something[i].name
        });

    }

}

you could retrieve keys from object and iterate through the list and see if the key is exist or not:

var keys=Object.keys(object)
for(var i=0;i<keys.length;i++){
     if(keys[i]=="your key"){//check your key here}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM