Get array of object's keys

前端 未结 7 1211
死守一世寂寞
死守一世寂寞 2020-11-22 05:41

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.

Is there a less verbose way than this?

var foo          


        
7条回答
  •  忘了有多久
    2020-11-22 06:06

    Summary

    For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.

    Example:

    const object = {
      a: 'string1',
      b: 42,
      c: 34
    };
    
    const keys = Object.keys(object)
    
    console.log(keys);
    
    console.log(keys.length) // we can easily access the total amount of properties the object has

    In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.

    Getting the values with: Object.values()

    The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:

    const object = {
      a: 'random',
      b: 22,
      c: true
    };
    
    
    console.log(Object.values(object));

提交回复
热议问题