Fastest way to flatten / un-flatten nested JSON objects

前端 未结 13 1312
孤城傲影
孤城傲影 2020-11-21 20:32

I threw some code together to flatten and un-flatten complex/nested JSON objects. It works, but it\'s a bit slow (triggers the \'long script\' warning).

For the flat

13条回答
  •  梦谈多话
    2020-11-21 21:07

    Use this library:

    npm install flat
    

    Usage (from https://www.npmjs.com/package/flat):

    Flatten:

        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
        // }
    

    Un-flatten:

    var unflatten = require('flat').unflatten
    
    unflatten({
        'three.levels.deep': 42,
        'three.levels': {
            nested: true
        }
    })
    
    // {
    //     three: {
    //         levels: {
    //             deep: 42,
    //             nested: true
    //         }
    //     }
    // }
    

提交回复
热议问题