js 有规则字符串映射对应结构的json

结构示例

1.我有一个这样的字符串:

let str = 'data.home.user.name';

2.我想让它生成一个对应结构json

{
    
    
    data:{
    
    
        home:{
    
    
            user:{
    
    
                name:''
            }
        }
    }
}

代码实现

let str = 'data.home.user.name';
let fatherJson,
    cureentJson = {
    
    };
const mappedTo = str.split('.');

// 开始处理
mappedTo.forEach((item, index) => {
    
    
    // 如果有fatherJson那么就将其子级的值设置为{}以便子级操作,否则就是首级
    fatherJson ? fatherJson[item] = {
    
    } : cureentJson[item] = {
    
    };
    if (fatherJson&&index >= (mappedTo.length - 1)) {
    
    
        // 对象的 最后一个属性,可以设置自己想要的值
        fatherJson[item]='鱼鱼'
    }
    // 将fatherJson设置为当前所在的json环境
    fatherJson = fatherJson ? fatherJson[item] : cureentJson[item];
});
console.log(cureentJson);
console.log(cureentJson.data.home.user);

总结

当我们遇到json结构循环处理时,我们通过理清father和son的关系就能很好的解决

猜你喜欢

转载自blog.csdn.net/z1783883121/article/details/120910070