简体   繁体   中英

Edit a deep part of an object with string key with dots

i need to merge two objects, where one is a part with some changes of an old one.

So, we have an object that looks like this (example):

{
   "item": {
      "data": "some text here",
      "info": {
         "test": {
            "roles": [
               "admin"
            ],
            "index": 0 
         }
      }
   }
}

and then we have a string that looks like this: "item.info.test" and also we have a new object, that is actually a part of an old one.

{
   "roles": [
      "admin"
   ],
   "index": 5  
}

how can we replace last subkey with a new object?

i tried using obj[key][subkey] etc, but its impossible to do this with lots of keys.

If you only need to deal with object keys not with array indexes, you could do something like this:

 const data = { "item": { "data": "some text here", "info": { "test": { "roles": [ "admin" ], "index": 0 } } } } const path = 'item.info.test'; const replacement = { "roles": [ "admin" ], "index": 5 }; const pathArray = path.split('.'); const lastKey = pathArray.pop(); const penultimate = pathArray.reduce((a, c) => a[c], data); penultimate[lastKey] = replacement; console.log(data);

This approach mutates the original object ( data ) and I've probably made it more complicated then it has to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM