我想用主对象中的其他对象替换子对象。
例如:
var mianobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var newsubobj = {"n":"8888","g":"9999"}
console.log(mainobj.a.aa)
// this gives the sub object --> {"aaa":"0000","bbb":"1111"}
我想用newsubobj
替换此对象。
我需要结果为::
console.log(mainobj);
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}
提前致谢。
答案 0 :(得分:4)
为什么你不这样做:
mainobj.a.aa = newsubobj
?
答案 1 :(得分:1)
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var subobjpath = "a.aa"; // this needs to be a string
var newsubobj = {"n":"8888","g":"9999"}
并且您希望使用subobjpath
将mainobj
的一部分替换为newsubobj
。
您可以使用以下代码执行此操作:
var path = subobjpath.split('.');
var obj = mainobj;
for(var idx=0; idx < path.length-1;idx++) obj = mainobj[path[idx]];
obj[path[path.length-1]] = newsubobj;
答案 2 :(得分:0)
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"};
var newsubobj = {"n":"8888","g":"9999"};
mainobj.a.aa = newsubobj;
console.log(mainobj);