Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
    }
]
like image 659
KenTenMen Avatar asked Sep 20 '13 17:09

KenTenMen


People also ask

How do you check if a key exist in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you check if key is not present in in object?

Example 2: Check if Key Exists in Object Using hasOwnProperty() The key exists. In the above program, the hasOwnProperty() method is used to check if a key exists in an object. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false .

How do you check if a key exists in an array of objects JavaScript?

Using hasOwnProperty() function The function hasOwnProperty() will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.

How do you check if a key value pair exists in an object JavaScript?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.


4 Answers

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) {}

like image 76
plalx Avatar answered Oct 13 '22 22:10

plalx


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 
}
like image 38
Tore Avatar answered Oct 13 '22 23:10

Tore


let data = {key: 'John'};
console.log( data.hasOwnProperty('key') );
like image 42
Bruno Oliveira Avatar answered Oct 13 '22 21:10

Bruno Oliveira


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?

like image 42
Kaibo Avatar answered Oct 13 '22 22:10

Kaibo