我有一棵樹,我想找到正確的節點并將資料插入到物件中。
const resultTree = {
grand_parent: {
parent: {
child: {},
},
sibling: {
cousin: {},
},
},
};
例如,將 grand_child 插入 child。
所以結果會是這樣的:
const resultTree = {
grand_parent: {
parent: {
child: {
grand_child: {}, // inserted grand_child here
},
},
sibling: {
cousin: {},
},
},
};
我可以根據需要插入更多,即將兄弟姐妹插入孩子
const resultTree = {
grand_parent: {
parent: {
child: {
grand_child: {},
sibling: {} // inserted sibling here
},
},
sibling: {
cousin: {},
},
},
};
這就是我現在擁有的,但它不起作用
const findAndInsert = (node: string, tree: Tree, parentNode: string) => {
if (!!tree[parentNode]) {
tree[parentNode][node] = {};
} else {
Object.keys(tree[parentNode]).forEach((n) => {
findAndInsert(node, tree[n], parentNode);
});
}
};
uj5u.com熱心網友回復:
主要問題是Object.keys(tree[parentNode]),正如您剛剛確認的那樣,parentNode密鑰不存在于tree. 相反,您想迭代現有的鍵。
我還建議您在插入后停止進一步查看。您可以通過回傳一個指示插入發生的布林值,然后使用someinstead of來實作這一點forEach。此外,您實際上不需要對鍵進行迭代,而是對值進行迭代,因此請使用Object.values:
const findAndInsert = (node, tree, parentNode) => {
if (!!tree[parentNode]) {
tree[parentNode][node] = {};
return true;
}
return Object.values(tree).some((n) =>
findAndInsert(node, n, parentNode)
);
};
const tree = {
grand_parent: {
parent: {
child: {},
},
sibling: {
cousin: {},
},
},
};
findAndInsert("grandchild", tree, "child");
findAndInsert("sibling", tree, "child");
console.log(tree);
uj5u.com熱心網友回復:
這個想法是正確的,看起來你有錯字,Object.keys(tree)而不是Object.keys(tree[parentNode]).
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537100.html
