A more efficient method for changing all corresponding properties located at varying depths within a nested object

When working with JSON data from an API, I often need to parse and modify specific property values. The challenge arises when the nesting structure of the JSON data is inconsistent and beyond my control.

For example, I cannot always rely on a fixed depth like parsedJson.children[0].property to find the desired property. It might be located at a different level, such as parsedJson.children[0].children[0].property in another instance.

Currently, I handle this by dynamically traversing the JSON object and modifying the desired property:

var parsedJson = JSON.parse('{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}')

console.log("before modify")
console.log(parsedJson)

modifyProperty(parsedJson,"p",1);

function modifyProperty(obj,prop,val){
    for (var key in obj){
        if (key == prop){
            obj[key] = val;
        }
        modifyProperty(obj[key],prop,val);
    }
}

console.log("after modify")
console.log(parsedJson)

However, I am concerned about potential performance issues when dealing with larger datasets and deeper nesting levels in future API responses. Repeatedly iterating through all child nodes could become inefficient.

Is there a more efficient or faster approach to accomplish this task?

Answer №1

If you want to transform all desired property values recursively in JSON.parse, you can pass a secondary parameter:

var transformedJson = JSON.parse(
  '{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}',
  (key, val) => key === 'p' ? 1 : val
);
console.log(transformedJson);

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

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Enhancing the security of a JSON web service

Having an issue with security of a json web service implementation. I attempted to create a sample web application using a json webservice, but the problem I encountered was that the url was visible on the client side. This means anyone could easily create ...

Reducing the amount of code within an if statement by utilizing JavaScript

I just finished coding a solution: if(!fs.existSync(path.join(data,file,path)){ fs.mkdirSync(path.join(data,file,path)); } if(!fs.existSync(path.join(another,file)){ fs.mkdirSync(path.join(another,file)); } if(!fs.existSync(path.join(new,file,temp,pa ...

Challenging to distinguish the JSON information

I am working with JSON data that looks like this: { "data":[ { "Products":{ "id":"86", "pname":"mi4", "pcat":"9", "subcat":"8", "seccat":"0", "oproduct":"1", "pdetails":"Good phone", ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Adjusting the color of a value in justGage requires a few simple steps to

Is it possible to modify the color and design of the text in the Value parameter of justGage after creating the gauge? My goal is to change the text color to blue with an underline to give it a link-like appearance. Appreciate your assistance. ...

Generating JSON using a column as a key in Azure SQL

In my SQL server table, I have the following data: Name Value ValueHash city 111 zzz address 333 yyy email [email protected] xxx name 222 www I need to retrieve the JSON format shown below using a SQL query { "address": { ...

Data exchange among sibling form components

I have a two-step form that is divided into switchable tabs. It is crucial for the user to seamlessly move from one tab to another without losing any information that has already been filled out. Therefore, I am looking for a solution to prevent React from ...

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

Is there a way to avoid adding this final "faulty state" to the array?

While working on dynamically slicing an array, I noticed that my while loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop(), I am curious ...

Managing code requiring document.title in Next.js with Static Site Generation (SSG)

Currently, I have 2 dynamic SSG pages located under /blog/[slug]. Within these pages, I am rendering a component using next/link. When I click on these links to navigate to another slug, I encounter an issue. The problem arises when I want to execute some ...

Organize unstructured JSON data using a specific method

My service returns a JSON with irregular data structure as shown below: dataFromService: [ { event_data: '2021-03-18T15:20:31.314Z', // if !null = page event_category: 'news', event_title_en: 'page title ...

EJS is refusing to render the HTML page

When utilizing Express with EJS to display the response from a database query as a basic Html page, an error is encountered in the development tools. "Access to fetch at 'https://o189131.ingest.sentry.io/api/5478725/envelope/?sentry_key=504fcb6 ...

Can JSON encoding in a URL pose a risk of XSS attacks?

To ensure my application has URL-friendly capabilities, I am storing its context as a JSON within the URL. This results in something like: http://mysite.dev/myapppage/target#?context={%22attr1%22%3A{%22target_id-0%22%3A{%22value%22%3A%223%22%2C%22label%2 ...

What is the best way to organize notifications by dates in a React application?

I'm currently working on a notifications component where I need to sort notifications by dates and then display them. Although I attempted the following code, it didn't work as intended: const result = notifications.notificationRows.sort((a, b) ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...