Utilize the map function to modify elements within a nested data structure

I'm attempting to modify objects within nested map functions. I have an array of objects with nested data.

When I try to execute it this way, the structure of the data changes and I end up with an array of arrays. All I really need is to add a "level" property to each object. Is it achievable using nested map functions?

const res = data.map(itemA => ({ ...itemA,
    level: 'a'
  })
  .subA.map(itemB => ({ ...itemB,
    level: 'b'
  })))

console.log(res)
<script>
  let data = [{
      name: 'testA1',
      subA: [{
          name: 'testB1',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        },
        {
          name: 'testB2',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        }
      ]
    },
    {
      name: 'testA2',
      subA: [{
        name: 'testB1',
        subB: [{
          name: 'testC1',
          subC: [{
            name: 'testD1',
            subD: []
          }]
        }]
      }]
    }
  ]
</script>

Answer №1

Are you familiar with using a recursive function?

let items = [{ name: 'testA1', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [] }] }, { name: 'testB2', subB: [{ name: 'testC1', subC: [] }] } ] }, 
            { name: 'testA2', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [{ name: 'testD1', subD: [] }] }] }] } ]

function addLevel(arr, level){
    arr.map(item => {
        const found = Object.keys(item).find(element => {
            if (element.includes('sub')) {
              return true;
            }
          });
          addLevel(item[found], level+1)
    })
    return arr.map(item => (item.level=level,item))
}

console.log(addLevel(items, 1))

Answer №2

Here is the approach I took:

const updatedData = data.map(itemA => (
  {...itemA, level: 'a', subA: itemA.subA.map(itemB => (
    {...itemB, level: 'b', subB: itemB.subB.map(itemC => (
      {...itemC, level: 'c'}
    ))}
  ))}
))
console.log(updatedData)
<script>
  let data = [{
      name: 'exampleA1',
      subA: [{
          name: 'exampleB1',
          subB: [{
            name: 'exampleC1',
            subC: []
          }]
        },
        {
          name: 'exampleB2',
          subB: [{
            name: 'exampleC1',
            subC: []
          }]
        }
      ]
    },
    {
      name: 'exampleA2',
      subA: [{
        name: 'exampleB1',
        subB: [{
          name: 'exampleC1',
          subC: [{
            name: 'exampleD1',
            subD: []
          }]
        }]
      }]
    }
  ]
</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

Issue with rendering Rails View using Javascript

In my show.html file, I have an <a ng-click="writeReview(product)" class="vote-link">Review</a> link. Within my javascript file, I have the following code: $scope.writeReview =(product) -> $http.get("/products/#{product.id}/review/new" ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...

Unable to load the JSON texture file

I recently exported a 3D model to JS from Blender, but I'm encountering an issue with the texture not showing up properly. Even when I remove the texture file, the browser generates an error saying that 'map.png' cannot be found. This indica ...

When sending a form with a POST request in NODE, the data can be missing

I'm having trouble with setting up routes in an API and getting data from simple forms. Take a look at this basic HTML form: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>test form</titl ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Route.get() function is expecting a callback function, but instead received a string object

Having searched through similar posts, I am unsure and lack the experience to apply the suggested resolutions to my project. I recently built a basic app with two main routes as part of a Udemy course, but I am struggling with the following error: "Route.g ...

Troubleshooting React: Child Component Fails to Render

Currently, I am enrolled in a React course and deep diving into the lifecycle methods of React. Through implementing componentDidMount, I have successfully made API calls and set the state accordingly. However, I am facing an issue with displaying images ...

How to retrieve ancestor route parameters in Angular?

My route structure is as follows: const appRoutes:Routes = [ { path: 'article', component: ArticleComponent, children: [ { path: '', component: ArticleListComponent }, { path: ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener. In my setup, the content.js file sends a message to the ba ...

When using JavaScript, an error may occur that says "Cannot read property 'style' of null," but strangely, this issue disappears when the code is copied and

I seem to be encountering an error in my codepen and I can't figure out what I'm doing wrong. It appears that I may have misplaced something, but I would greatly appreciate any help or explanation of my mistake. function on() { document ...

Utilize AJAX to insert information into a MySQL database when a checkbox is selected

Before I got stuck here, I took a look at how a similar question was implemented here I attempted to implement the code in order to insert data into a MySQL database when a checkbox is clicked. While it may have been easier to do this on form submission, ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

Leveraging webpack for CSS bundling

I'm currently working on bundling some NPM modules using webpack instead of utilizing a CDN. While I've successfully managed to integrate the .js files, I'm facing challenges with including the .css files for these modules. One example is ...

Storing JavaScript code in a PHP variable fails to function

I've encountered an issue with my JavaScript code. <script> $(document).ready(function(){ $('.delete').click(function() { alert('passed'); }); }); </script> Everything work ...

The error message "npm ReferenceError: primordials is not defined (node.js)" indicates that the

I have encountered this issue multiple times and despite attempting various solutions, I am unable to resolve it. I am currently working with npm and facing the following error: evalmachine.<anonymous>:35 } = primordials; ^ ...