Fastest way to flatten / un-flatten nested JSON objects

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

    Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)

    Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.

    JSON.unflatten = function(data) {
        "use strict";
        if (Object(data) !== data || Array.isArray(data))
            return data;
        var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
            props = Object.keys(data),
            result, p;
        while(p = props.shift()) {
            var m = regex.exec(p),
                target;
            if (m.index) {
                var rest = p.slice(0, m.index);
                if (!(rest in data)) {
                    data[rest] = m[2] ? [] : {};
                    props.push(rest);
                }
                target = data[rest];
            } else {
                target = result || (result = (m[2] ? [] : {}));
            }
            target[m[2] || m[1]] = data[p];
        }
        return result;
    };
    

    It currently uses the data input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf usage performs better than the regex (depends on the regex engine).

    See it in action here.

提交回复
热议问题