我的五分钱。
对于想要展平对象而不是属性的情况
换句话说。
你有这样的事情:
var obj = {
one_a: {
second_a: {
aaa: 'aaa',
bbb: 'bbb'
},
second_b: {
qqq: 'qqq',
third_a: {
www: 'www',
eee: 'eee',
fourth_a: {
'rrr': 'rrr',
fifth: {
ttt: 'ttt'
}
},
fourth_b: {
yyy: 'yyy',
}
},
third_b: {
'uuu': 'uuu'
}
}
},
one_b: {
iii: 'iii'
}
}
并且想让嵌套对象变平,但不想变平属性:
{ 'one_a second_a ': { aaa: 'aaa', bbb: 'bbb' },
'one_a second_b ': { qqq: 'qqq' },
'one_a second_b third_a ': { www: 'www', eee: 'eee' },
'one_a second_b third_a fourth_a ': { rrr: 'rrr' },
'one_a second_b third_a fourth_a fifth ': { ttt: 'ttt' },
'one_a second_b third_a fourth_b ': { yyy: 'yyy' },
'one_a second_b third_b ': { uuu: 'uuu' },
'one_b ': { iii: 'iii' } }
代码:
function flatten (obj, includePrototype, into, prefix) {
into = into || {};
prefix = prefix || "";
for (var k in obj) {
if (includePrototype || obj.hasOwnProperty(k)) {
var prop = obj[k];
if (prop && typeof prop === "object" && !(prop instanceof Date || prop instanceof RegExp)) {
flatten(prop, includePrototype, into, prefix + k + " ");
}
else {
if (into[prefix] && typeof into[prefix] === 'object') {
into[prefix][k] = prop
} else {
into[prefix] = {}
into[prefix][k] = prop
}
}
}
}
return into;
}
基于闭包的回答