Javascript以参数方式设置对象值

时间:2014-09-26 19:00:54

标签: javascript variables object

有没有办法用可变路径设置对象值?例如,给定对象

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)

0 个答案:

没有答案