Utilizing JavaScript recursion to navigate through a JSON object and update specific key-value pairs on its nested children

Exploring a JSON object structure that follows a tree-like child-parent relationship. Each node in the structure has a unique ID. Attempting to iterate through the entire object using a recursive function, encountering challenges with handling the children nodes.

Below is the JSON object structure:

    {
    "id": 1,
    "recursoId": {
        "id": 1,
        "tipoRecurso": {
            "id": 5,
            "nombre": "Base de datos PostgreSQL",
            "icono": "fas fa-database"
        },
        "alias": "Base de datos Producción (Retama)",
        "nombre": "Retama",
        "propietario": {
            "id": 4,
            "nombre": "Sistemas"
        },
        "servicio012": false
    },
    ...
}

Here is the code snippet where "instancias" is the complete object:

jsonAdapter(instancias: any) {
    Object.entries(instancias).forEach((entry) => {
      const [key, value] = entry;
      if (key === 'recursoId') {
        Object.entries(value).forEach((recursoIdEntry) => {
          const [key, value] = recursoIdEntry;
          if (key === 'tipoRecurso') {
            Object.entries(value).forEach((tipoRecursoEntry) => {
              const [key, value] = tipoRecursoEntry;
            })
          }
          if (key === 'propietario') {
            Object.entries(value).forEach((propietarioEntry) => {
              const [key, value] = propietarioEntry;
            })
          }
        })
      }
      if ((key === 'children') && value) {
        for (let i = 0; i < entry.length; i++) {
          this.jsonAdapter(value[i]);
        }
      }
    });
  }

Upon execution, the code correctly processes the first branch of the tree structure. However, subsequent iterations consistently return undefined. Need assistance in resolving this issue. Thank you!

Answer №1

The recursive function "leaves" processes leaf key/value pairs by recursively iterating through them, with the containing object provided for reference. In this specific case, the function is used to rename all instances of the "nombre" key to "renamed_nombre".

function leaves(obj, callback) {
  for (let property in obj) {
    if (obj.hasOwnProperty(property) && obj[property] != null) {
      if (typeof obj[property] === 'object') {
        leaves(obj[property], callback);
      } else if (Array.isArray(obj[property])) {
        for (let i = 0; i < obj[property].length; i++) {
          leaves(obj[property][i], callback);
        }
      } else {
        callback(obj, property, obj[property])
      }
    }
  }
}

let bigObject = getBigObject()
leaves(bigObject, (object, key, value) => {
  if (key === 'nombre') {
    object.renamed_nombre = value
    delete object[key]
  }
})
console.log(JSON.stringify(bigObject, null, 4))


function getBigObject() {
  return {
    "id": 1,
    "recursoId": {
      "id": 1,
      "tipoRecurso": {
        "id": 5,
        "nombre": "Base de datos PostgreSQL",
        "icono": "fas fa-database"
      },
      "alias": "Base de datos Producción (Retama)",
      "nombre": "Retama",
      "propietario": {
        "id": 4,
        "nombre": "Sistemas"
      },
      "servicio012": false
    },
    ...

Answer №2

The issue lies in the final if condition where a loop is being used with entry.length, which will always yield 2 due to each entry containing a key and a value pair. Even if the 'children' key is empty, the entry would be ["children", []] with a length of 2. To address this, it is recommended to use the length of the value instead:

if ((key === 'children') && value) {
    for (let i = 0; i < value.length; i++) {
        this.jsonAdapter(value[i]);
    }
}

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

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

What could be causing the error within the 'react-code-blocks' library?

Currently, I am involved in a project that utilizes Typescript and React. However, I have encountered an issue while working with the 'react-code-blocks' library. The structure of my container component is as follows: interface ICodeBlockProps { ...

Extracting a precise value from JSON using PHP

Currently, I am attempting to extract the price data from the JSON provided below, but I am struggling to identify the correct reference for the actual values: {"cards": [ { "high": "0.73", "volume": 1, "percent_change": "-2.67", "name": "Lightning Bolt", ...

When running locally, the Web API functions as expected. However, once published, it

After successfully creating a Web API that returns data using AngularJS and displaying it on a local web page, I encountered an issue when I published the API to my web host. The error message "SyntaxError: JSON.parse: unexpected end of data at line 1 colu ...

The JSON object cannot be converted into a string format in PHP

I am currently working with a piece of PHP code that is designed to receive a number sent from an Android app. The code's purpose is to search for the equivalent value of that number in the database, specifically in another field, and then send the re ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...

"Confusion arises when handling undefined arguments within async.apply in the context of async

While working on my project, I encountered a strange issue with the async library. Some of my arguments end up being "undefined" in my function calls. For example (this is just simplifying my problem): var token; async.series([ function getToken (do ...

What is the best way to utilize an "as" property in TypeScript when forwarding props to a component?

I am currently working on creating a collection of components, and I require some of them to have the option of a customizable tag name. For instance, there are times when what seems like a <button> is actually an <a>. Therefore, I would like t ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

There are two distinct varieties of object arrays

I recently encountered an issue while trying to sort my array of Star Wars episodes by episode ID. The problem emerged when comparing two arrays: one manually inputted in the code snippet labeled as "1" on the screenshot, and the other generated dynamicall ...

Ensure that the link's color remains constant and remove any styling of text-decoration

Attempting to create a customized header. My goal is to change the color and remove text decoration in the navbar. Below is my code snippet: ReactJS: import React from 'react'; import './Header.css'; function Header() { return ( ...

Angular 2: trigger a function upon the element becoming visible on the screen

How can I efficiently trigger a function in Angular 2 when an element becomes visible on the screen while maintaining good performance? Here's the scenario: I have a loop, and I want to execute a controller function when a specific element comes into ...

Risk Score Generating Form

As I work on a comprehensive form, there are 5 sections for users to mark if they qualify (using checkmarks). The form consists of approximately 50 questions in total. Each section carries different weights/points (e.g., Section 1 is worth 1 point each, ...

Is there a way to make a model behave like an object in loopback when typing?

One of the challenges I face is dealing with a loopback model that is often represented in raw JSON format. For example: @model() class SomeModel extends Entity { @property({ type: 'string' }) id?: string; } In its raw JSON form, it would l ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...

Is it possible to prevent certain values from being converted into numeric when using json_encode?

Whenever I utilize PHP (5.4/5.5) along with the json_encode() function, I encounter some difficulties when implementing the JSON_NUMERIC_CHECK parameter. It's a live system, so removing the option is not an ideal solution as it would disrupt the respo ...

I attempted to access the content of an Array that I had mapped, but unfortunately, I was unable to reach it due to an undefined error (no

My plan is to display a series of questions from my JSON database in order to create a quiz. The function I wrote loads the questions and maps them. However, I encounter an issue where I cannot access the questions array ('question' is not define ...

A guide on using sinon to stub express middleware in a typescript project

I'm currently facing a challenge in writing an integration test for my express router using typescript, mocha, sinon, and chai-http. The router incorporates a custom middleware I created to validate JWT tokens present in the header. My goal is to moc ...

Avoid automatic restart of NestJS server upon modifying specific directories

When running my application in watch mode using the nest start --watch command, the server automatically restarts whenever a source file is changed. While this behavior is expected, I am looking for a way to exclude certain directories or files from trigg ...