0

I need to search and replace value from a nested object using javascript. I am explaining the object below.

let jsonObj = {
    "service":[
        {
            "name":"restservice",
            "device":"xr-1",
            "interface-port":"0/0/2/3",
            "interface-description":"uBot testing for NSO REST",
            "addr":"10.10.1.3/24",
            "mtu":1024
        }
    ],
    "person": {
    "male": {
      "name": "infinitbility"
    },
    "female": {
      "name": "aguidehub",
      "address": {
           "city": "bbsr",
           "pin": "752109"
      }
    }
  }
}

In the above nested object I need to search the key and replace the value. Here my requirement is in the entire object it will search for the key name and where ever it is found it will replace the value as BBSR. In the above case there are 3 place where name key is present so I need to replace the value accordingly using Javascript.

subhra_user
  • 439
  • 5
  • 19
  • 2
    Where's the code you've attempted to solve this? It's no good giving us your requirements because SO isn't a code-writing service. We help people with _their code_ that doesn't work. Add your code to the question as a [mcve]. – Andy May 18 '22 at 05:02
  • Seems like [this](https://stackoverflow.com/questions/15523514/find-by-key-deep-in-a-nested-array) thread would be helpful for you – DGX37 May 18 '22 at 05:03

1 Answers1

2

You can try the deep search algorithm
Iterate over the entire object
Determine the current property
If the current property is object or array
then continue to recurse the property
If the property is not an object or array
then determine if the object's key == 'name'
if yes, then do what you want to do
If not, then do nothing
like this

const deepSearch = (target) => {
    if (typeof target === 'object') {
        for (let key in target) {
            if (typeof target[key] === 'object') {
                deepSearch(target[key]);
            } else {
                if (key === 'name') {
                    target[key] = 'xxx'
                }
            }
        }
    }
    return target
}