Home >Web Front-end >JS Tutorial >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; };
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 && prop) result[prop] = {}; } } recurse(data, ""); return result; };
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!