Created
February 13, 2019 09:24
-
-
Save wxingheng/3d04ef425c21f018830d8e07993ae4e0 to your computer and use it in GitHub Desktop.
js对象扁平化与反扁平化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```language | |
Object.flatten = function(obj){ | |
var result = {}; | |
function recurse(src, prop) { | |
var toString = Object.prototype.toString; | |
if (toString.call(src) == '[object Object]') { | |
var isEmpty = true; | |
for (var p in src) { | |
isEmpty = false; | |
recurse(src[p], prop ? prop + '.' + p : p) | |
} | |
if (isEmpty && prop) { | |
result[prop] = {}; | |
} | |
} else if (toString.call(src) == '[object Array]') { | |
var len = src.length; | |
if (len > 0) { | |
src.forEach(function (item, index) { | |
recurse(item, prop ? prop + '.[' + index + ']' : index); | |
}) | |
} else { | |
result[prop] = []; | |
} | |
} else { | |
result[prop] = src; | |
} | |
} | |
recurse(obj,''); | |
return result; | |
} | |
Object.unflatten = function(data) { | |
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; | |
} | |
Object.unflatten2 = function(data) { | |
if (Object(data) !== data || Array.isArray(data)) | |
return data; | |
var result = {}, cur, prop, idx, last, temp; | |
for(var p in data) { | |
cur = result, prop = "", last = 0; | |
do { | |
idx = p.indexOf(".", last); | |
temp = p.substring(last, idx !== -1 ? idx : undefined); | |
cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {})); | |
prop = temp; | |
last = idx + 1; | |
} while(idx >= 0); | |
cur[prop] = data[p]; | |
} | |
return result[""]; | |
} | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
扁平化了一下 扁平化