乐趣区

关于javascript:js-对象根据路径修改值

var obj = {
    "zhang":{
        name:'张三',
        girlfriend:{name:'阿狸',}
    }
}

var path = 'zhang-girlfriend-name'
var value = '娑娜'

function setVal(){var list = path.split("-");
    var th = "";
    for (let i = 0; i < list.length; i++) {th += "['" + list[i] + "']";
    }
    eval(`obj${th}='${value}'`)
} 

 
  • 运行后果
{
    "zhang":{
        name:'张三',
        girlfriend:{name:'娑娜',}
    }
}
退出移动版