鍍金池/ 問(wèn)答/人工智能  HTML/ 算法小問(wèn)題:指定類(lèi)型數(shù)組轉(zhuǎn)換成對(duì)象的問(wèn)題。

算法小問(wèn)題:指定類(lèi)型數(shù)組轉(zhuǎn)換成對(duì)象的問(wèn)題。

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

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

需要將上面的數(shù)組轉(zhuǎn)換成一個(gè)指定格式的對(duì)象object:

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

可能看起來(lái)有點(diǎn)復(fù)雜,不過(guò)思路應(yīng)該還是挺清晰的,應(yīng)該是一個(gè)遞歸的過(guò)程,但是本人算法是在不是很好,求大神給一個(gè)解決方案

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

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

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

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

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

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

                // 將子節(jié)點(diǎn)對(duì)象加入 map 和父節(jié)點(diǎn)的 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