开发者

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

开发者 https://www.devze.com 2023-02-15 22:58 出处:网络
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\"}

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

精彩评论

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