Fastest way to flatten / un-flatten nested JSON objects

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

    ES6 version:

    const flatten = (obj, path = '') => {        
        if (!(obj instanceof Object)) return {[path.replace(/\.$/g, '')]:obj};
    
        return Object.keys(obj).reduce((output, key) => {
            return obj instanceof Array ? 
                 {...output, ...flatten(obj[key], path +  '[' + key + '].')}:
                 {...output, ...flatten(obj[key], path + key + '.')};
        }, {});
    }
    

    Example:

    console.log(flatten({a:[{b:["c","d"]}]}));
    console.log(flatten([1,[2,[3,4],5],6]));
    

提交回复
热议问题