字符串反扁平化 字符串转对象

字符串反扁平化

-- 转化 obj1 转为 obj2
-- 用到loadsh 可以用for循环替换成原生的

var obj1=[
    { name: 'xx1.xx2.xx11',
        message: '问题1',
        value: '212',
        validate: 1 },
        { name: 'xx1.xx21.xx3',
        message: '问题2',
        value: '323',
        validate: 1 },
]


var obj2={
    xx1:{
        xx2:{
            xx11:'212'
        },
        xx21:{
            xx3:'323'
        }
    }
}


//将obj name value取出
function unFlattenedobj(handlebarsJsonArrParams){
    const handlebarsObj={}
    _.forEach(handlebarsJsonArrParams,(itemArr)=>{
        handlebarsObj[itemArr.name]=itemArr.value
    })
    return  unFlattened(handlebarsObj)
//{ 'xx1.xx2.xx11': '212', 'xx1.xx21.xx3': '323' }
}


 function  unFlattened(data) {
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder = {};
    for (var p in data) {
        var cur = resultholder,
            prop = "",
            m;
        while (m = regex.exec(p)) {
            cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[""] || resultholder;
    //{ xx1: { xx2: { xx11: '212' }, xx21: { xx3: '323' } } }
}


console.log(unFlattenedobj(obj1))
//{ xx1: { xx2: { xx11: '212' }, xx21: { xx3: '323' } } }

参考链接

  • https://www.cnblogs.com/mengff/p/7097011.html

你可能感兴趣的:(字符串反扁平化 字符串转对象)