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

Dealing with AJAX error in pure JavaScript

I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective. function ajaxPost(url, data, success, error) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () ...

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

The typescript compiler encounters an error when processing code that includes a generator function

Recently, I started learning about TypeScript and came across the concept of generators. In order to experiment with them, I decided to test out the following code snippet: function* infiniteSequence() { var i = 0; while(true) { yield i++ ...

Having issues with Craco not recognizing alias configuration for TypeScript in Azure Pipeline webpack

I am encountering an issue with my ReactJs app that uses Craco, Webpack, and Typescript. While the application can run and build successfully locally, I am facing problems when trying to build it on Azure DevOps, specifically in creating aliases. azure ...

Utilizing a relationship's remote method in Loopback

My current project involves using loopback where I have a MyUser model that is related (hasMany) to a SellerRequests model. After discovering that I can create a new seller request linked to the user by making a POST request to /api/MyUsers/:id/sellerRequ ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

Executing a nested function before moving on to the subsequent code statements

I have a requirement where certain functions in my codebase need to check if a user is logged in before proceeding. Instead of duplicating this check logic, I want to call a single getUser() function each time. Here is the order of operations for the func ...

Invoke a function from a different source in JavaScript

Below is the JS function implemented: function addMemberToLessonDirect(id) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ...

Send the model to the route to be filled through the query parameter

I'm currently working on a task that involves creating a function to handle app routes. The goal is to pass in an object that will be filled with the fields from the request body. In my code snippet below, I encountered an error mentioning that ' ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

I encountered the issue: "The specified resource is not a valid image for /public/logoicon/logoOrange.png, it was received as text/html; charset=utf-8."

I encountered an issue when trying to incorporate a PNG or SVG file into my code. What steps should I take to correct this error and enable the images to display properly? import Head from 'next/head' import Image from 'next/image' impo ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Tips for creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

Stop Chrome from automatically scrolling to the top of the page when making changes to the DOM

Currently utilizing Action Cable to create a discussion room where users can exchange questions. Upon posting a question, all participants within the room are supposed to see it. Nonetheless, I've encountered an odd issue specifically on Chrome: whene ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Angular does not include the ControlGroup feature in its common offerings

I am new to TypeScript and have been following tutorials in an attempt to accomplish simple tasks, but so far without success. Many tutorials seem outdated with changes in Angular or provide instructions that do not work at all. Even the tutorials that do ...