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

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

將字符串樹轉換為數組

將字符串樹轉換為數組

素胚勾勒不出你 2021-06-14 13:01:26
我有一個 id 作為字符串的對象。每個對象都可以是另一個對象的子對象??梢詮?ID 猜測關系。舉個例子:[  { id: '1:2:6', ids: ['1', '2', '6'] },  { id: '1:4', ids: ['1', '4'] },  { id: '1', ids: ['1'] },  { id: '1:2', ids: ['1', '2'] },]在這個例子中,根對象是id: 1,它有 2 個孩子id: 1:2和id: 1:4。終于,id: 1:2有了孩子id: 1:2:6。我想將此數組轉換為另一個數組,其中兒童嵌入到父母中,因此前一個數組將導致:[  {    id: '1',    children: [      {        id: '1:2',        children: [          { id: '1:2:6', children: [] }        ],      },      {        id: '1:4',        children: [],      }    ],  }]我可以使用 ES6。我嘗試了幾個小時來使用各種循環找到解決方案,但我無法弄清楚。任何幫助,將不勝感激!
查看完整描述

3 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

您可以ids通過在實際級別查找對象來迭代對象并減少對象。如果沒有找到創建一個新對象。然后讓孩子們回來。


var data = [{ id: '1:2:6', ids: ['1', '2', '6'] }, { id: '1:4', ids: ['1', '4'] }, { id: '1', ids: ['1'] }, { id: '1:2', ids: ['1', '2'] }],

    tree = data.reduce((r, { ids }) => {

        ids.reduce((t, _, i, a) => {

            var id = a.slice(0, i + 1).join(':'),

                temp = t.find(o => o.id === id);

            

            if (!temp) t.push(temp = { id, children: [] });

            return temp.children;

        }, r);

        return r;

    }, []);


console.log(tree);

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


查看完整回答
反對 回復 2021-06-18
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

使用遞歸算法構建樹


var jsonTree = [{ id: '1:2:6', ids: ['1', '2', '6'] },{ id: '1:4', ids: ['1', '4'] },{ id: '1', ids: ['1'] },{ id: '1:2', ids: ['1', '2'] },]


var newJsonTree = [];

var currentElement = {id: '1',childs: []}

newJsonTree.push(currentElement)


function buildTree(jsonTree, currentElement){

    for(var i=0;i<jsonTree.length;i++){

        var parent = jsonTree[i];

        for(var j=0;j<jsonTree.length;j++){

            var child = jsonTree[j];

            if(child['visited'] != true && child['id'] != currentElement['id'] && child['id'].indexOf(currentElement['id']) == 0 ){

                if(child['id'].split(":").length == currentElement['id'].split(":").length+1){

                    var newElement = {}

                    newElement['id'] = child['id'];

                    newElement['childs'] = [];

                    currentElement['childs'].push(newElement);

                    child['visited'] = true;

                    buildTree(jsonTree, newElement);

                }

            }

        }

    }

}


buildTree(jsonTree, currentElement);

document.write(JSON.stringify(newJsonTree));

結果:


[{"id":"1","childs":[{"id":"1:4","childs":[]},{"id":"1:2","childs":[ {"id":"1:2:6","childs":[]}]}]}]




查看完整回答
反對 回復 2021-06-18
  • 3 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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