Get array of object's keys

前端 未结 7 1323
死守一世寂寞
死守一世寂寞 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:02

    In case you're here looking for something to list the keys of an n-depth nested object as a flat array:

    const getObjectKeys = (obj, prefix = '') => {
      return Object.entries(obj).reduce((collector, [key, val]) => {
        const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
        if (Object.prototype.toString.call(val) === '[object Object]') {
          const newPrefix = prefix ? `${prefix}.${key}` : key
          const otherKeys = getObjectKeys(val, newPrefix)
          return [ ...newKeys, ...otherKeys ]
        }
        return newKeys
      }, [])
    }
    
    console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))

提交回复
热议问题