是否可以用主对象中的其他对象替换子对象?

时间:2011-03-09 13:28:57

标签: javascript

我想用主对象中的其他对象替换子对象。

例如:

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"}

提前致谢。

3 个答案:

答案 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"}

并且您希望使用subobjpathmainobj的一部分替换为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);