flatten(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, "");
console.log(result, "423423");
return result;
},
调用:
this.flatten({
a: {
b: 1,
c: 2,
d: { e: 5 },
},
b: [1, 3, { a: 2, b: 3 }],
c: 3,
});
网友评论