Skip to content

Instantly share code, notes, and snippets.

@wxingheng
Created February 13, 2019 09:24
Show Gist options
  • Save wxingheng/3d04ef425c21f018830d8e07993ae4e0 to your computer and use it in GitHub Desktop.
Save wxingheng/3d04ef425c21f018830d8e07993ae4e0 to your computer and use it in GitHub Desktop.
js对象扁平化与反扁平化
```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[""];
}
```
@lqzhgood
Copy link

扁平化了一下 扁平化

Object.prototype.flatten = function (src = this, prop = '', result = {}) {
    const toString = Object.prototype.toString;
    if (toString.call(src) == '[object Object]') {
        const isEmpty = true;
        for (const p in src) {
            if (Object.hasOwnProperty.call(src, p)) {
                isEmpty = false;
                flatten(src[p], prop ? prop + '.' + p : p, result);
            }
        }
        if (isEmpty && prop) {
            result[prop] = {};
        }
    } else if (toString.call(src) == '[object Array]') {
        const len = src.length;
        if (len > 0) {
            src.forEach((item, index) => {
                flatten(item, prop ? prop + '.[' + index + ']' : index, result);
            });
        } else {
            result[prop] = [];
        }
    } else {
        result[prop] = src;
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment