Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows:

My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's children.

For example - From the given response, there are two objects "Africa" and "Europe". Therefore, I want to combine the children of "Europe" with the parent children of "Africa".

Could anyone assist me in achieving the desired output?

findChildrens(){
     this.newRegion = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          },
          {
            "name": "Test2",
            "region": "South Africa",
          },
          {
            "name": "Test3",
            "region": "New Test",
          }
        ]
      },
      {
        "name": "Europe",
        "children": [
          {
            "name": "Test4",
            "region": "1UL Africa"
          },
          {
            "name": "Test5",
            "region": "Test Europe"
          }
        ]
      }
    ];    
  };
  
  };

Expected Result

this.newRegion = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          },
          {
            "name": "Test2",
            "region": "South Africa",
          },
          {
            "name": "Test3",
            "region": "New Test",
          },
           {
            "name": "Test4",
            "region": "1UL Africa"
          },
          {
            "name": "Test5",
            "region": "Test Europe"
          }
        ]
      }     
    ];    
  };

Answer №1

Do you have a project in mind similar to this?

let freshArea = [
      {
        "name": "Asia",
        "children": [
          {
            "name": "Trial1",
            "region": "1UL Asia"
          },
          {
            "name": "Trial2",
            "region": "South Asia",
          },
          {
            "name": "Trial3",
            "region": "New Trial",
          }
        ]
      },
      {
        "name": "North America",
        "children": [
          {
            "name": "Trial4",
            "region": "1UL America"
          },
          {
            "name": "Trial5",
            "region": "Sample North America"
          }
        ]
      }
    ];  
    
    let outcome=freshArea[0];
    if(freshArea.length>1){
    result.children=result.children.concat(freshArea.slice(1).map(obj=>obj.children).flat())
    }
    
    console.log(outcome)

Answer №2

Perhaps this function could serve your needs, but I must caution you that what you are attempting to accomplish lacks scalability and does not adhere to best practices in coding. It may be beneficial to adjust the code so that it functions properly regardless of the number of regions.

// Storing this data in a constant might be more efficient
const REGIONS = [
  {
    "name": "Africa",
    "children": [
      {
        "name": "Test1",
        "region": "1UL Africa"
      },
      {
        "name": "Test2",
        "region": "South Africa",
      },
      {
        "name": "Test3",
        "region": "New Test",
      }
    ]
  },
  {
    "name": "Europe",
    "children": [
      {
        "name": "Test4",
        "region": "1UL Africa"
      },
      {
        "name": "Test5",
        "region": "Test Europe"
      }
    ]
  }
];

findChildren() {
  if (Object.keys(REGIONS).length > 1) {
    const mergedChildren = REGIONS[0].children.concat(REGIONS[1].children);
    return ({
      ...REGIONS[0],
      children: mergedChildren
    })
  } else {
    return REGIONS[0];
  }
}

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

Universal form submission via ajax

Issue with ajax/javascript: I am working on an application that includes multiple forms. My goal is to create a generic JavaScript function that can submit forms to their respective controllers by using the form ID. I have successfully retrieved the form I ...

How can I parse JSON in React using the Parse function?

I am currently working with three list components, and when I click on any item in the tree list, it displays the JSON data. However, I would prefer to view it in a parse format rather than JSON. I attempted to use let json = JSON.parse(this.props.node, n ...

Modifying child text in React when hovering over a button

How can I update the text of a child function component when hovering over a button in the parent class component? I am struggling to access the prop in the child component and keep getting null. Any assistance would be greatly appreciated. Parent Compone ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Angular Select displays a MatIcon along with the selected value

My code looks like this: <mat-select > <mat-option *ngFor="let option of options" [value]="option.id" [disabled]="option.disabled" [matTooltip]="option.tooltip" > & ...

State loss occurs when moving to a different page using next/link

Currently, I am working on a library application with Next.js. Within this project, there are two main pages: BooksPage, which displays a list of all books, and BookPage, where detailed information about a specific book is shown. The components involved in ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...

What is the best way to accomplish a smooth transition of background colors similar to this design

I was browsing different websites and stumbled upon this amazing background color transition that caught my attention. I really liked it and now I want to create something similar on my own website. Despite my best efforts, I haven't been able to achi ...

Using Promise.all for multiple function calls

I have several functions set up like this: private async p1(): Promise<Result> { let p1; // Do some operations. return p1; } private async p5(): Promise<void> { // Make a call to an external API. } Some of these functions c ...

What is the best way to streamline the creation of a "products filter" using Node.js and Angular?

I have decided to build an angular application for an online computer store, and I am using a node/express backend. One of the key features of the application is the products page, where users can view all the products available in our database. Each produ ...

Something is seriously wrong with the datetime in fullcalendar JavaScript

I've been diving into a tutorial for creating a calendar scheduler in asp.net MVC5 from this link. One issue I'm facing is the datetime being passed and stored as the min value in the database (1/1/0001 12:00:00 AM), almost like it's null b ...

Click to add a different template into the document

My HTML page consists of a form with multiple input fields and a carousel. Towards the bottom of the form, there is a button labeled Add another quote. This button essentially duplicates the input fields above (all contained within class="quote"). Here&ap ...

Working with Angular2: Linking dropdown values with any number of items

Is there a way to dynamically bind drop down values with numbers from 1 to 100 using a loop in Angular2? I am currently using Ngprime dropdown for a limited number of values, but how can I achieve this for any number of values? Here is the template: < ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

Is three too much for the Javascript switch statement to handle?

I'm a beginner in Javascript and am working on a project to create a fun program involving astrological signs, planets, and houses to generate a story. I have included three switch statements within one function to accomplish this. I'm encounter ...

How can I move a nested child component out of an ancestor element with overflow set to hidden?

I'm facing an issue with a sliding carousel where the overflow-x property is set to hidden. The carousel displays 4 items at a time, and each item contains a button that triggers a pop-out menu positioned relative to its parent item. The problem arise ...

Developing a universal.css and universal.js file for a custom WordPress theme

I have developed a custom WordPress theme with an extensive amount of code. To manage the numerous style and script files, I have segmented them into multiple individual files. To integrate all these files into my template, I utilized the following code w ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

When the Angular+gsap3 animation fails to trigger on click

app.component.html <div #animate class="main"> <div id="go" (click)="click()" class="box1"></div> <div class="box"></div> <div class="box"></di ...

Error in React .js: Unable to access property 'name' as it is undefined

I keep encountering this issue: Uncaught TypeError: Cannot read property 'name' of undefined In my code, I have a user object defined in the App.js file. However, when I attempt to access its properties within my Person component, it throws a ...