在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/人工智能  HTML/ 算法小問題:指定類型數(shù)組轉換成對象的問題。

算法小問題:指定類型數(shù)組轉換成對象的問題。

有如下形式的二維數(shù)組:

array = [
    ["北京市","海淀區(qū)"],
    ["北京市","東城區(qū)"],
    ["遼寧省","沈陽市","和平區(qū)"],
    ["遼寧省","沈陽市","鐵西區(qū)"],
    ["臺灣省"]
]

需要將上面的數(shù)組轉換成一個指定格式的對象object:

targetObject = {
    text:"",
    children: [
        {
            text: '北京市',
            children: [
                {
                    text: '海淀區(qū)',
                    children: [],
                },{
                    text: '東城區(qū)',
                    children: []
                }
            ]
        },{
            text: '遼寧省',
            children: [
                {
                    text: '沈陽市',
                    children: [
                        {
                            text: '和平區(qū)',
                            children: []
                        },{
                            text: '鐵西區(qū)',
                            children: []
                        }
                    ]
                }
            ]
        },{
            text: '臺灣省',
            children: []
        }
    ]
}

可能看起來有點復雜,不過思路應該還是挺清晰的,應該是一個遞歸的過程,但是本人算法是在不是很好,求大神給一個解決方案

回答
編輯回答
葬愛
const array = [
    ["北京市", "海淀區(qū)"],
    ["北京市", "東城區(qū)"],
    ["遼寧省", "沈陽市", "和平區(qū)"],
    ["遼寧省", "沈陽市", "鐵西區(qū)"],
    ["臺灣省"]
];

function convert(list) {
    // map 用來保存已處理節(jié)點的字典,
    // 鍵是城市的全路徑(/分隔),
    // 值是根據(jù)城市名稱產生的對象
    const map = {};

    // 根節(jié)點對象
    const root = {
        text: "",
        children: []
    };

    list.forEach(parts => {
        // 對 parts 中的每一個城市進行處理
        // reduce 主要用于拼接 key,即全路徑
        parts.reduce((parentKey, name) => {
            // 根據(jù)父節(jié)點的 key 和當前城市名稱拼接當前城市 key
            const key = `${parentKey}/${name}`;

            // 如果節(jié)點已經存在,直接跳過
            if (!map[key]) {
                // 先用 parentKey 找到父節(jié)點,如果沒有,用 root 作為父節(jié)點
                const parent = map[parentKey] || root;

                // 產生子節(jié)點對象
                const node = {
                    text: name,
                    children: []
                };

                // 將子節(jié)點對象加入 map 和父節(jié)點的 children
                map[key] = node;
                parent.children.push(node);
            }

            return key;
        }, "");
    });

    return root;
}

const r = convert(array);
console.log(JSON.stringify(r, null, 4));
2017年1月23日 02:35