使用
{ _id: "123", super: { super: { super: { someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}}}}
{ _id: "123", someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}
这样做的好方法是什么?最好使用下划线。
答案 0 :(得分:3)
您需要递归地合并对象,同时检查所需的密钥:
var data = {
_id: "123",
super: {
super: {
super: {
someString: "here",
someOtherString: "here",
someObject: {
withSomeContents: true
}
}
}
}
};
function merge(dest, src) {
Object.keys(src).forEach(function(key) {
dest[key] = src[key];
});
}
function flattenKey(data, flatKey) {
return Object.keys(data).reduce(function(obj, key) {
if (key === flatKey) {
merge(obj, flattenKey(data[key], flatKey));
} else {
obj[key] = data[key];
}
return obj;
}, {});
}
document.getElementById('r').textContent = JSON.stringify(flattenKey(data, 'super'));

<pre id=r></pre>
&#13;