美文网首页
字符串反扁平化 字符串转对象

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

作者: 栀璃鸢年_49a3 | 来源:发表于2020-11-16 09:55 被阅读0次

    字符串反扁平化

    -- 转化 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.haomeiwen.com/subject/mnsabktx.html