Fastest way to flatten / un-flatten nested JSON objects

前端 未结 13 1233
孤城傲影
孤城傲影 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:29

    You can use https://github.com/hughsk/flat

    Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.

    Example from the doc

    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
    // }
    
    
    var unflatten = require('flat').unflatten
    
    unflatten({
        'three.levels.deep': 42,
        'three.levels': {
            nested: true
        }
    })
    
    // {
    //     three: {
    //         levels: {
    //             deep: 42,
    //             nested: true
    //         }
    //     }
    // }
    

提交回复
热议问题