基于一次性密钥展平
Flatten based on disposable key
有
{ _id: "123", super: { super: { super: { someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}}}}
带有超级键的关卡可以任意深,我希望每个关卡及其内容都被压平,以便得到
{ _id: "123", someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}
这样做的好方法是什么?最好使用下划线。
您需要递归合并对象,同时检查所需的键:
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>
有
{ _id: "123", super: { super: { super: { someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}}}}
带有超级键的关卡可以任意深,我希望每个关卡及其内容都被压平,以便得到
{ _id: "123", someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}
这样做的好方法是什么?最好使用下划线。
您需要递归合并对象,同时检查所需的键:
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>