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.

2
  • 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 minimal reproducible example. Commented May 18, 2022 at 5:02
  • Seems like this thread would be helpful for you Commented May 18, 2022 at 5:03

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.