如何遍历节点树并修改其结构和值



这是我的输入。它的一些节点由具有其他多个节点的下线组成。

data = [
{
"user_id": "1",
"username": "johndoe001",
"amount": "0.00",
"downlines": [
{
"user_id": "2",
"username": "j001-01",
"amount": "1.00",
"downlines": []...

如何将其转换为如下输出?

[
{
"key": "1",
"label": "johndoe001 (0.00)",
"nodes": [
{
"key": "2",
"label": "j001-01 (1.00)",
"nodes": []...

我可以使用简单的字符串替换来部分完成,但我未能将标签值修改为usernameamount的组合。在此之后,我也无法删除不需要的密钥,如amount

let stringJson = JSON.stringify(data);
stringJson = stringJson.replace(/downlines/g, 'nodes');
stringJson = stringJson.replace(/username/g, 'label');
stringJson = stringJson.replace(/user_id/g, 'key');
let tmpTree = JSON.parse(stringJson);

这通过递归函数变得非常简单:

const data = [
{
"user_id": "1",
"username": "johndoe001",
"amount": "0.00",
"downlines": [
{
"user_id": "2",
"username": "j001-01",
"amount": "1.00",
"downlines": []
},
]
},
];
function rename(downlines) {
return downlines.map(({ user_id, username, amount, downlines }) => ({
key: user_id, // rename user_id to key
label: `${username} (${amount})`, // format label
nodes: rename(downlines), // now do the same to the rest
}));
}
console.log(rename(data));

如果您对({ ... }) =>语法感到困惑,请参阅析构函数。

最新更新