// way 1
setTimeout(() => {
    let convertData = resolveDataString(DataString);
    console.log(`convertData  => `, convertData);
}, 0);
/**
 * use while
 *
 * @param {object} obj
 * @return {*}
 */
function resolveData(obj: object): object {
    let result: object = {};
 
    let keyValue = Object.entries(obj);
    for (const [key, value] of keyValue) {
        // Split key keys array
        const keys: string[] = key.split('.');
 
        // Create sub-objects along key as needed
        let target: object = result;
        while (keys.length > 1) {
            const shiftKey = keys.shift();
            let targetValue = (target[shiftKey] = target[shiftKey] || {});
            target = targetValue;
            // target = target[shiftKey] = target[shiftKey] || {};
        }
 
        // Set value at end of path
        target[keys[0]] = value;
    }
 
    return result;
}
 
function resolveDataString(data: string): any {
    let result: object = {};
 
    let dataObj = data.split('\n');
 
    dataObj.forEach((data) => {
        let splitData: string[] = data.split('=');
        result[splitData[0]] = splitData[1];
    });
 
    return resolveData(result);
}
 
// way 2
setTimeout(async () => {
    let strs: string[][] = DataString .split(/(\r)?\n/)
        .filter((n) => !!n)
        .map((n) => n.split(/\.|=/).filter((n) => !!n));
 
    let obj: object = {};
    for (let i: number = 0; i < strs.length; i++) {
        Cut(obj, strs[i]);
    }
 
    console.log(JSON.stringify(obj, null, 4));
}, 0);
 
/**
 * use recursive
 *
 * @param {object} obj
 * @param {string[]} keys
 */
function Cut(obj: object, keys: string[]) {
    if (keys.length > 2) {
        if (!obj[keys[0]]) {
            obj[keys[0]] = {};
        }
        Cut(obj[keys[0]], keys.splice(1, keys.length - 1));
    } else {
        console.log(keys);
        if (/[0-9]/.test(keys[1])) obj[keys[0]] = parseInt(keys[1]);
        else if (/true|false/.test(keys[1])) obj[keys[0]] = keys[1] === 'true';
        else obj[keys[0]] = keys[1];
    }
}
 
const DataString = `scheduleView.today.en-US=Today
scheduleView.today.zh-CN=true
scheduleView.today.zh-TW=当天
scheduleView.today.ko-KR=123
scheduleView.today.ja-JP=오늘
scheduleView.tues.en-US=Tues.
scheduleView.tues.zh-CN=false
scheduleView.tues.zh-TW=周二
scheduleView.tues.ko-KR=456
scheduleView.tues.ja-JP=화요일
scheduleView.week.fri.en-US=fri.
scheduleView.week.fri.zh-CN=true
scheduleView.week.fri.zh-TW=五
scheduleView.week.fri.ko-KR=789
scheduleView.week.fri.ja-JP=ブランド`;
arrow
arrow
    創作者介紹
    創作者 bingzhichen 的頭像
    bingzhichen

    空境界

    bingzhichen 發表在 痞客邦 留言(2) 人氣()