這是我的輸入。它的一些節點由具有其他多個節點的下線組成。
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": []...
我可以使用簡單的字串替換部分完成,但我未能將標簽值修改為username
和的組合amount
。在此之后,我也無法洗掉不需要的密鑰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);
uj5u.com熱心網友回復:
使用遞回函式,這變得非常簡單:
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));
如果您對語法感到困惑,請參閱解構。({ ... }) =>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527583.html
標籤:打字稿
上一篇:cdk無法連接到unix:///var/run/docker.sock上的Docker守護程式。docker守護行程是否正在運行?-部署cdk時出錯