Getting JavaScript object key list

后端 未结 17 1140
野性不改
野性不改 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:11
    var keys = new Array();
    for(var key in obj)
    {
       keys[keys.length] = key;
    }
    
    var keyLength = keys.length;
    

    to access any value from the object, you can use obj[key];

    0 讨论(0)
  • 2020-11-22 02:13

    Underscore.js makes the transformation pretty clean:

    var keys = _.map(x, function(v, k) { return k; });
    

    Edit: I missed that you can do this too:

    var keys = _.keys(x);
    
    0 讨论(0)
  • 2020-11-22 02:18
           if(props.userType){
              var data = []
              Object.keys(props.userType).map(i=>{
                    data.push(props.userType[i])
              })
              setService(data)
            }
    
    0 讨论(0)
  • 2020-11-22 02:19

    Using ES6, you can use forEach to iterate over the Keys of an Object. To get all the keys you can use Object.keys which returns all the keys in an Object

    Object.keys(obj).forEach(function(keyValue, index, map) { 
      console.log(keyValue); 
    });
    

    Short hand of the above snippet would be, which only takes one parameter

    Object.keys(obj).forEach(function(keyValue) { 
      console.log(keyValue); 
    });
    
    0 讨论(0)
  • 2020-11-22 02:20

    var obj = {
       key1: 'value1',
       key2: 'value2',
       key3: 'value3',
       key4: 'value4'
    };
    var keys = [];
    
    for (var k in obj) keys.push(k);
    
    alert("total " + keys.length + " keys: " + keys);

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