开发者

Is it possible to replace sub object with other object in main object?

I want to replace the sub object with some other object in main object.

ex:

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

I want to replace this object with newsubobj.

I need the result as ::

console.log(mainobj); 
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}

Thanks in advance.


Why you don't do it like that: mainobj.a.aa = newsubobj ?


Ah, now we're getting somewhere. To update your question you have:

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

and you want to use subobjpath to replace a part of mainobj with newsubobj.

You can do so using code like this:

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;


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜