Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined 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 example, I want to find and replace specific values within the nested object. Specifically, I need to locate all instances of the key name and update the value to BBSR. With three occurrences of the name key in the object, I will use JavaScript to perform these replacements.

Answer №1

If you are looking to implement a thorough search algorithm, consider using the deep search method.
Start by looping through the entire object and analyzing each property individually.
Check if the current property is an object or an array.
If it is, continue to recursively iterate over that property.
If the property is a simple value (not an object or array), check if its key matches 'name'.
If the key does match 'name', execute your desired action.
If not, move on to the next property.
Follow this structured approach to efficiently navigate through complex data structures.

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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

Jsonip.com is providing both internal and external IP addresses

I'm utilizing to retrieve the IP address of users. In some cases, it is returning both an internal and external IP as a string separated by commas. I am interested in only obtaining the external IP address. Can I assume a specific order for the retur ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

Update your Django database with new information either using views or a JSON dictionary

My simplest table structure is as follows: class Player(models.Model): number = models.CharField(max_length=2) player = models.CharField(max_length=50) position = models.CharField(max_length=2) height = models.CharField(max_length=50) weight = models.Char ...

Insert a Facebook like button within a designated div

Can anyone figure out why the Facebook button isn't functioning properly? ---- ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

How to programmatically close a Liferay dialog box

I am currently dealing with a Liferay dialog box. My goal is to close this dialog box and then redirect the URL to a specific page. This is how I am attempting to achieve it: <aui:column columnWidth="16" > <%if(UserGroupRoleLocalServiceUtil.has ...

What is the best way to manage an out of bounds exception within a Json object?

I'm encountering an issue with a function that returns a Json object like this: return Json( db.Select(c => new GridViewModel() { Number = c.Rows[0][0].ToString(), DocId = c. ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

When utilizing styled-jsx alongside postcss, experiencing issues with styles failing to reload or rebuild

I'm currently using postcss in conjunction with styled-jsx. In my setup, I have multiple CSS files that I'm importing using the @import directive within the _app.js file. Everything seems to work smoothly, except when I modify any of the CSS file ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

How to include a root node in a JSON variable using Logic apps?

As I attempt to achieve the following task: @xml(json(concat('\\"rootnode\\":',variables('TestJSON')))) However, the issue that arises is: InvalidTemplate. Unable to process template language expressions ...

Having difficulty in loading Socket.io client .js file?

I am currently facing an issue deploying a socket.io chat on Heroku. While the page loads successfully, the client's socket.io js file is not being downloaded, resulting in the chat functionality not working. Attached are images showcasing the error ...

What is the best way to access the parent document of a Firestore collectionGroup query?

I'm currently working on accessing the parent documents of all subcollection queries in my database structure. The setup I am aiming for is something like this: /production/id/position/id/positionhistory While I have successfully retrieved all the d ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Utilizing analytics.js independently of the react-ga library

Is there a way to integrate Google Analytics into my React app without using the react-ga package? I specifically want to access the ga function in a separate JavaScript file as well as within a React component. How can I achieve this by importing the anal ...

What is the best way to extract information from a JSON array stored in a

I have JSON data stored in a file. { "from_excel":[ { "solution":"Fisrt", "num":"1" }, { "solution":"Second", "num":"2" }, { "solution":"third", "num":"3" }, { "solution": ...

Partial functionality achieved by integrating Bootstrap for a modal form in Rails

Having an issue with a form in a partial view on Rails 3.2.3 utilizing the bootstrap 2.0.2 modals #myModal.modal .modal-header .close{"data-dismiss" => "modal"}= link_to "x", root_path %h3 Add Tags .modal-body = form_tag '/tagging& ...

The request is not functioning as expected for some reason

My current challenge involves retrieving photos from Instagram using a GET request. I attempted to use jQuery.get(), which has been successful for other types of GET requests but not for Instagram. Despite trying to switch to jQuery.getJSON(), the issue pe ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...