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

How Can I Efficiently Flatten and Unflatten Nested JavaScript Objects?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 00:41:13179browse

How Can I Efficiently Flatten and Unflatten Nested JavaScript Objects?

Flattening and Unflattening Nested JavaScript Objects

Flattening and unflattening nested JavaScript objects can be an essential task in many applications. However, it can be a complex and computationally expensive operation. In this article, we will explore two approaches to flattening and unflattening nested objects that can significantly improve performance.

Efficient Flattening and Unflattening

The first approach, proposed by Bergi, focuses on using a regular expression to parse the object keys and efficiently navigate the object structure. Here is the code for the unflattening function:

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;
};

For the flattening function, it's recommended to omit the "isEmpty" checks to improve performance:

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 + "]");
        } else {
            for (var p in cur) {
                recurse(cur[p], prop ? prop+"."+p : p);
            }
        }
    }
    recurse(data, "");
    return result;
}

Non-Regex Approach

The second approach, proposed by Bergi and further modified by AaditMShah, avoids using regular expressions and relies solely on string operations to parse the object keys. This approach is particularly efficient when the object keys follow certain naming conventions.

Object.unflatten = function(data) {
    "use strict";
  if (Object(data) !== data || Array.isArray(data)) return data;
  var result = {};
  for (var key in data) {
    var parts = key.split('.'),
      cur = result;
    for (var i = 0; i < parts.length; i++) {
      if (!cur[parts[i]]) {
        cur[parts[i]] = (i == parts.length - 1) ? data[key] : {};
      }
      cur = cur[parts[i]];
    }
  }
  return result[""] || result;
};
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; i < cur.length; i++)
        recurse(cur[i], prop + "[" + i + "]");
    } else {
      var isEmpty = true;
      for (var p in cur) {
        isEmpty = false;
        recurse(cur[p], prop ? prop + "." + p : p);
      }
      if (isEmpty) result[prop] = {};
    }
  }
  recurse(data, "");
  return result;
};

Performance Results

The provided benchmarks show that these approaches can significantly improve the performance of flattening and unflattening nested objects, offering a substantial speed increase compared to the original code. These techniques are particularly beneficial in scenarios where large and complex objects need to be processed efficiently.

The above is the detailed content of How Can I Efficiently Flatten and Unflatten Nested 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