Search code examples
javascriptkeybraces

Javascript count keys in braces of function


I call a function like so:

update_insert('information',{
    element_id: 1,
    type: 'menu',
    info: 'Hi how are ya?',
    new_window: ''
});

The function is:

function update_insert(table,data){
    alert(data.length);
}

I am trying to get the number of keys that I inserted into the function, and eventually get the names of the keys, dynamically with a loop. How can I achieve this?


Solution

  • Objects don't have the .length attribute like arrays do in JavaScript. You'll need to use a function to count the number of items in an object:

    getObjectLength = function(obj) {
    
        var size = 0, key;
    
        for (key in obj) {
            if (obj.hasOwnProperty(key))
                size++;
        }
    
        return size;
    }
    

    EDIT:

    And to get the keys from an object:

    getObjectKeys = function(obj) {
    
        var keys = [];
    
        for (var key in obj) {
            keys.push(key);
        }
    
        return keys;
    }