Fastest way to flatten / un-flatten nested JSON objects

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

    I'd like to add a new version of flatten case (this is what i needed :)) which, according to my probes with the above jsFiddler, is slightly faster then the currently selected one. Moreover, me personally see this snippet a bit more readable, which is of course important for multi-developer projects.

    function flattenObject(graph) {
        let result = {},
            item,
            key;
    
        function recurr(graph, path) {
            if (Array.isArray(graph)) {
                graph.forEach(function (itm, idx) {
                    key = path + '[' + idx + ']';
                    if (itm && typeof itm === 'object') {
                        recurr(itm, key);
                    } else {
                        result[key] = itm;
                    }
                });
            } else {
                Reflect.ownKeys(graph).forEach(function (p) {
                    key = path + '.' + p;
                    item = graph[p];
                    if (item && typeof item === 'object') {
                        recurr(item, key);
                    } else {
                        result[key] = item;
                    }
                });
            }
        }
        recurr(graph, '');
    
        return result;
    }
    

提交回复
热议问题