Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array.

Issue: The code seems to enter the first if statement correctly, but the updated result is not being returned in the end. Instead, the input array of objects is always returned. What could be causing this problem?

FUNCTION:

export function findChild(array: any, id: string): array {
                return array.map((node) => {
                    if (node.id === id) {
                        return { ...node, status: 'Activated' };
                    } else {
                        if (node.children?.length) {
                            findChild(node.children, id);
                        }
                        
                    }
            
                    return node;
                });
            }

Plain JS

function findChild(array, id) {
  return array.map((node) => {
    if (node.id === id) {
      return { ...node, status: 'Activated' };
    } else {
      if (node.children?.length) {
        findChild(node.children, id);
      }
    }
    return node;
  });
}

findChild(input,7)
   console.log(input)
**INPUT** This is just an example of input. The array of objects have multiple children and I have to go through all ids to check the condition and then update the value of status


<script>
  let input = [{
      id: '1',
      amt: '30',
      status: 'Active',
      children: [{
          id: 'SG2',
          amt: '305',
          status: 'Active',
        },
        {
          id: '5',
          amt: '30',
          status: 'Active',
          children: [],
        },
      ],
    },
    {
      id: '6',
      amt: '307',
      status: 'Active',
      children: [],
    },
    {
      id: '7',
      amt: '40',
      status: 'Inactive',
      children: [{
        id: '7',
        amt: '40',
        status: 'Inactive',
        children: []
      }],
    },
    {
      id: '8',
      amt: '100',
      status: 'Dead',
      children: [],
    },
  ];
  </script>

Answer №1

Give this a try

export function updateNodeStatus(array: any, id: string, status: string): array {
  return array.map((node) => {
    if (node.id === id)
      node.status = status;
    else if (node.children != null && node.children.length > 0) 
      node.children = updateNodeStatus(node.children, id, status);
    return node;
  });
}

Executing code snippet

function updateNodeStatus(array, id, status){
  return array.map((node) => {
    if (node.id === id)
      node.status = status;
    else if (node.children != null && node.children.length > 0) 
      node.children = updateNodeStatus(node.children, id, status);
    return node;
  });
}


updateNodeStatus(input,7, 'Activated')
console.log(input)
**INPUT** This is an example representing input data structure with multiple nested nodes each having unique identifiers for identification and status updates

<script>
  let input = [{
      id: '1',
      amt: '30',
      status: 'Active',
      children: [{
          id: 'SG2',
          amt: '305',
          status: 'Active',
        },
        {
          id: '5',
          amt: '30',
          status: 'Active',
          children: [],
        },
      ],
    },
    {
      id: '6',
      amt: '307',
      status: 'Active',
      children: [],
    },
    {
      id: '7',
      amt: '40',
      status: 'Inactive',
      children: [{
        id: '7',
        amt: '40',
        status: 'Inactive',
        children: []
      }],
    },
    {
      id: '8',
      amt: '100',
      status: 'Dead',
      children: [],
    },
  ];
  </script>

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

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

Create boilerplate code easily in VS Code by using its feature that generates code automatically when creating a

Is there a way to set up VS Code so that it automatically creates Typescript/React boilerplate code when I create a new component? import * as React from "react"; export interface props {} export const MyComponent: React.FC<props> = (): J ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

Issue with Angular and rxjs: Subscription provider not found

Trying to establish communication between a service and component in Angular, where the service holds a value and the component subscribes to its changes. Currently utilizing rxjs Subscription, but encountering an issue: Uncaught (in promise): Error: No p ...

Stop Internet Explorer from automatically scrolling when it gains focus

Please access this fiddle using internet explorer (11): https://jsfiddle.net/kaljak/yw7Lc1aw/1/ When the page loads, the <p> tag is focused and Internet Explorer slightly scrolls the element so that the table border becomes invisible... document.qu ...

Struggling with error management while using react-redux during the SignUp process

https://i.sstatic.net/OD2fl.pngWithin my component code, I handle user sign up and error checking. Initially, the error value is null. let error = useSelector((state) => state.authReducer.error); const checkErrorLoading = () => { ...

Update the image source every 1 second with Jquery and Javascript

I've been experimenting with creating a script that dynamically changes the source of an image every two seconds based on a list. Essentially, my current approach involves using a for loop to iterate over the provided list: $(document).ready(functio ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...

Challenge encountered while using the like operator with Integer data type in Mongoose

I am encountering an issue with constructing a where query in Mongoose for an integer data type. The key 'facevalue' is of integer data type. When I execute a find query, it appears something like this: Below is the code snippet: var orCond ...

What is the purpose of using an open quote and bracket in the `eval('('+jsonString+')')` syntax for parsing a JSON string?

What is the rationale behind this particular syntax structure? eval('(' + jsonString+ ')') When it comes to parsing JSON text, Crockford explains that "The text must be wrapped in parentheses to prevent any confusion with JavaScript& ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

How can specific times be disabled using Laravel-9 jQuery Timepicker?

$(document).ready(function(){ $('#time').timepicker({ timeFormat: 'h:mm a', interval: 60, minTime: '9', maxTime: '4:00pm', defaultTime: '9', startTime: '9:00', dyna ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

Gulp: Adding to Dest without Overwriting

I have the following code snippet: gulp.task('concat-uglify-js', function() { return gulp.src(src + 'js/*.js') .pipe(concat('angular-filemanager.min.js')) .pipe(uglify()) .pipe(gulp.dest(dst)) }); gulp.task(&ap ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...

Parent component not receiving value from NG_VALUE_ACCESSOR for radio button selections

Within the parent component, I have developed a form that is intended to function with 3 sets of radio buttons. My approach involved using NG_VALUE_ACCESSOR for communication between the parent and child components. While the data transfer from parent to c ...

Issue with TypeScript Functions and Virtual Mongoose Schema in Next.js version 13.5

I originally created a Model called user.js with the following code: import mongoose from "mongoose"; import crypto from "crypto"; const { ObjectId } = mongoose.Schema; const userSchema = new mongoose.Schema( { //Basic Data ...