Getting JavaScript object key list

后端 未结 17 1141
野性不改
野性不改 2020-11-22 01:27

I have a JavaScript object like

var obj = {
   key1: \'value1\',
   key2: \'value2\',
   key3: \'value3\',
   key4: \'value4\'
}

How can I

相关标签:
17条回答
  • 2020-11-22 02:04

    using slice, apply and join method.

    var print = Array.prototype.slice.apply( obj );
    alert('length='+print.length+' list'+print.join());
    
    0 讨论(0)
  • 2020-11-22 02:05

    Recursive solution for browsers that support ECMAScript 5:

    var getObjectKeys = function(obj) {
        var keys = Object.keys(obj);
        var length = keys.length;
    
        if (length !== 0) {
            for (var i = 0; i < length; i++) {
                if (typeof obj[keys[i]] === 'object') {
                    keys[keys[i]] = getObjectKeys(obj[keys[i]]);
                }
            }
        }
    
        return keys;
    };
    
    0 讨论(0)
  • 2020-11-22 02:06
    var obj = {
       key1: 'value1',
       key2: 'value2',
       key3: 'value3',
       key4: 'value4'
    }
    
    console.log(Object.keys(obj));
    console.log(Object.keys(obj).length)
    
    0 讨论(0)
  • 2020-11-22 02:06

    If you decide to use Underscore.js you better do

    var obj = {
        key1: 'value1',
        key2: 'value2',
        key3: 'value3',
        key4: 'value4'
    }
    
    var keys = [];
    _.each( obj, function( val, key ) {
        keys.push(key);
    });
    console.log(keys.lenth, keys);
    
    0 讨论(0)
  • 2020-11-22 02:09

    In JavaScript, an object is a standalone entity, with properties and type.

    For fetching values from Object in form of array: Object.values(obj) // obj is object name that you used Result -> ["value1", "value2", "value3", "value4"]

    For fetching keys from Object in form of array: Object.keys(obj) // obj is object name that you used Result -> ["key1", "key2", "key3", "key4"]

    As both functions are returning array you can get the length of keys or value by using length property. For instance - Object.values(obj).length or Object.keys(obj).length

    0 讨论(0)
  • 2020-11-22 02:10
    obj = {'a':'c','b':'d'}
    

    You can try:

    [index for (index in obj)] 
    

    this will return:

    ['a','b']
    

    to get the list of keys or

    [obj[index] for (index in obj)]
    

    to get the values

    0 讨论(0)
提交回复
热议问题