j.doe:
私は以下のような構造を持っています:
{
0: [{
"id": "1",
"parentId": "root",
"path": "root"
"children": [{
"id": "2",
"parentId": "1",
"path": "1/2",
"children": [
"id": "4",
"parentId": "2",
"path": "2/4"
]
}, {
"id": "3",
"parentId": "1",
"path": "1/3"
}]
}]
}
私は、キー持ち"path"
、今ではだ"parentId/id"
、が、私はこの要素にルートからのパスを持っていると思いますのでべきルックス"root/parentId/id/parentId/it..."
例えば、パスの場合など:"root/1/2/4"
。
どのように私は動的にキー内の値を置くことができる"path"
ルート要素へのフルパスを取得するには?
Guerric P:
あなたのデータ構造は、各要素の子供時代を尊重していないが、これを考慮すると、問題の一部ではありませんんが、ここでは簡単な再帰的解決策は以下のとおりです。
const data = [{
"id": "1",
"parentId": "root",
"path": "root",
"children": [{
"id": "2",
"parentId": "1",
"path": "1/2",
"children": [{
"id": "4",
"parentId": "2",
"path": "2/4"
}
]
}, {
"id": "3",
"parentId": "1",
"path": "1/3"
}
]
},
{
"id": "4",
"parentId": "2",
"path": "2/4"
}
];
function assignPath(tree, index, array, currentPath) {
tree.path = currentPath || 'root';
tree.children && tree.children.forEach(child => {
assignPath(child, null, null, `${tree.path}/${child.id}`);
});
}
data.forEach(assignPath);
console.log(data);