[英]Recursively create nested object with dynamic keys
我對遞歸很滿意,但遇到了需要使用變量鍵創建嵌套對象的情況。 已經看到其他建議使用諸如“bc”之類的命名空間約定來確定在何處深度分配值(請參閱下面的所需 output),但難以實現。 該結構可以無限嵌套。
// Source
const input = {
a: {
type: 'string',
ex: '1'
},
b: {
type: 'object',
another: {
c: {
type: 'string',
ex: '2'
}
}
}
}
// Desired
const output = {
a: '1',
b: {
c: '2'
}
}
// The attempt
function traverse(data, master = {}) {
Object.entries(data).reduce((collection, [key, value]) => {
switch (value.type) {
case 'string':
collection[key] = value.ex;
break;
default:
collection[key] = traverse(value.another, collection);
}
return collection;
}, master);
}
運行此返回undefined
。
嵌套traverse
應該得到一個全新的 object 作為第二個參數,您還需要從 function 返回一個結果,嘗試:
// Source const input = { a: { type: 'string', ex: '1' }, b: { type: 'object', another: { c: { type: 'string', ex: '2' } } } } // The attempt function traverse(data, master = {}) { return Object.entries(data).reduce((collection, [key, value]) => { switch (value.type) { case 'string': collection[key] = value.ex; break; default: collection[key] = traverse(value.another, {}); } return collection; }, master); } console.log(traverse(input));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.