有没有办法用可变路径设置对象值?例如,给定对象
var top = {node:{id:{ip:"1.2.3.4"}}};
可以新值
var newIp = "1.1.1.1";
替换路径上的值:
var path = "node.id.ip";
注意:
eval("top." + path); // This gets the value parametrically
// How to set the value parametrically?
感谢mithunsatheesh提供答案。以下作品:
var top = {node:{id:{ip:"1.2.3.4"}}};
var path = "node.id.ip";
var newVal = "1.1.1.1";
eval("top." + path+ "=newVal;");
JSON.stringify(top)