Home >Web Front-end >JS Tutorial >How Can I Efficiently Flatten and Unflatten JavaScript Objects?

How Can I Efficiently Flatten and Unflatten JavaScript Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 00:35:10198browse

How Can I Efficiently Flatten and Unflatten JavaScript Objects?

Fast and Efficient Flattening and Unflattening of JavaScript Objects

Flattening and unflattening nested JavaScript objects is a common task in web development, but it can be computationally intensive. This article explores efficient implementations for both flattening and unflattening operations.

Flattening Objects

The following code provides a highly optimized flattening implementation:

Object.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop ? prop+"."+i : i);
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+"."+p : p);
            }
            if (isEmpty &amp;&amp; prop)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

Unflattening Objects

For unflattening, the following implementation demonstrates improved performance:

Object.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder = {};
    for (var p in data) {
        var cur = resultholder,
            prop = "",
            m;
        while (m = regex.exec(p)) {
            cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[""] || resultholder;
};

Benchmark Results

These implementations significantly improve performance in flattening and unflattening operations. In Opera 12.16, flattening is about twice as fast (~900ms instead of ~1900ms), while in Chrome 29, it improves by around the same rate (~800ms instead of ~1600ms).

Caution:

Note that these implementations, focused on speed, are susceptible to prototype pollution. Therefore, it is essential to avoid using them on untrusted objects.

The above is the detailed content of How Can I Efficiently Flatten and Unflatten JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn