Best way to flatten JS object (keys and values) to a single depth array

前端 未结 10 952
梦毁少年i
梦毁少年i 2020-12-05 05:10

I have written this small function to get all keys and values of an object and store them into an array. The object might contain arrays as values...

Object {

10条回答
  •  青春惊慌失措
    2020-12-05 05:48

    If you're feeling really lazy then you can make use of the popular NPM library flat.

    Example (from their docs)

    var flatten = require('flat')
    
    flatten({
        key1: {
            keyA: 'valueI'
        },
        key2: {
            keyB: 'valueII'
        },
        key3: { a: { b: { c: 2 } } }
    })
    
    // {
    //   'key1.keyA': 'valueI',
    //   'key2.keyB': 'valueII',
    //   'key3.a.b.c': 2
    // }
    

提交回复
热议问题