亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在javascript中將樹從graphql格式轉換為json格式

在javascript中將樹從graphql格式轉換為json格式

jeck貓 2022-01-07 09:54:12
我正在嘗試從這種格式轉換客戶端的數據:[{    "id": 1,    "name": "dad",    "parent": [],    "children": [{            "group": {                "id": 2,                "name": "child1",                "parent": [{                    "parent": 1                }]            }        },        {            "group": {                "id": 3,                "name": "child2",                "parent": [{                    "parent": 1                }]            }        },        {            "group": {                "id": 8,                "name": "child3",                "parent": [{                    "parent": 1                }]            }        }    ]}]到這種格式:[{    id: 1,    name: "parent",    parent: null,    children: [{            id: 2,            name: "child1",            parent: {                id: 1            },            children: []        },        {            id: 3,            name: "child2",            parent: {                id: 1            },            children: []        }    ]}]關鍵點:所有鍵都不應該是字符串類型“父母”應該只包括父母的ID'group' 對象應該被刪除 - 它的內容應該只是替換他我在 npm 中找不到要使用的轉換庫,并且我需要將數據采用精確的格式才能在“react-vertical-tree”組件中使用(在 react 中沒有找到任何其他好看的垂直樹組件)。
查看完整描述

1 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

您可以使用轉換后的部分映射新對象。


const convert = o => {

    var children;

    if ('group' in o) o = o.group;

    if ('children' in o) children = o.children.map(convert);

    return Object.assign({}, o, { parent: o.parent.length ? { id: o.parent[0].parent } : null }, children && { children });

};


var data = [{ id: 1, name: "dad", parent: [], children: [{ group: { id: 2, name: "child1", parent: [{ parent: 1 }] } }, { group: { id: 3, name: "child2", parent: [{ parent: 1 }] } }, { group: { id: 8, name: "child3", parent: [{ parent: 1 }] } }] }],

    result = data.map(convert);


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反對 回復 2022-01-07
  • 1 回答
  • 0 關注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號