Home > Web Front-end > JS Tutorial > How Can I Optimize Flattening and Unflattening Nested JavaScript Objects?

How Can I Optimize Flattening and Unflattening Nested JavaScript Objects?

Linda Hamilton
Release: 2024-12-29 08:30:11
Original
880 people have browsed it

How Can I Optimize Flattening and Unflattening Nested JavaScript Objects?

Unflattening and Flattening Nested JavaScript Objects: Optimized Implementations

The task of flattening and un-flattening complex JavaScript objects can be time-consuming. Here's a comprehensive analysis to optimize this operation:

The challenge: A JavaScript object needs to be flattened with "." as the delimiter for object keys and "[INDEX]" for arrays.

Initial solution: The provided code solves the problem but is relatively slow.

Faster implementation (using regular expressions): Bergi introduces a significantly faster implementation using regular expressions. It unflattens the object by iterating through the flattened properties and creating nested structures accordingly.

Fastest implementation (non-regex): Building on Bergi's concept, the provided implementation offers the fastest non-regex version. It assumes specific rules for key names, excluding integers at the start or periods within the name.

Improving unflattening performance: AaditMShah enhances the unflatten performance by employing inline path parsing instead of String.split in the nested loop.

Final code (unflatten):

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;
};
Copy after login

Final code (flatten):

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 + "[" + 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;
};
Copy after login

These optimizations significantly improve the performance of flattening and un-flattening nested JavaScript objects while adhering to Browser compatibility requirements.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template