What is the best way to organize and rearrange the JSON object within Angular8?

I received the following response and I need to reorganize all the data and its children based on the buSubRegion that is currently nested within the children. Additionally, I need to add the buSubRegion outside of the children.

For example: In the response below, 1UL Africa belongs to the Africa object and is also present within the Europe object, so I want to merge the children of all objects related to 1UL Africa into one array of objects.

If a buSubRegion has the same value and is present in multiple objects, then I need to find all those objects and merge them into one.

Also, Agbara - Savoury does not have a BU sub-region so I do not want to include this object.

Can someone please help me achieve this?

const data = [
    ...
];

Below is the expected output:

[
    ...
];

Answer №1

To effectively group the data by buSubRegion, you can utilize the reduce method along with looping through the children property.

const data = [{"name":"Africa","id":1,"children":[{"name":"Agbara - Laundry","buSubRegion":"1UL Africa","children":[{"lineId":"R_D005_TPKDST02"}]},{"name":"Agbara - Savoury","children":[{"lineId":"R_D005_TPKDST02"}]}]},{"name":"Europe","id":2,"children":[{"name":"Europe1","buSubRegion":"1UL Africa","children":[{"lineId":"R_D005_TPKDST02"}]},{"name":"Europe2","buSubRegion":"Test Europe","children":[{"lineId":"R_D005_TPKDST02"}]}]},{"name":"Latem","id":3,"children":[{"name":"test1","buSubRegion":"latem1","children":[{"lineId":"R_D005_TPKDST02"}]}]}];

const result = data.reduce((a,{children, ...rest})=>{
    children.forEach(({buSubRegion,...others})=>{
        if(buSubRegion){
            a[buSubRegion] ??= {buSubRegion, ...rest, children:[]};
            a[buSubRegion].children.push({buSubRegion, ...others})
        }
    });
    return a;
},{});
console.log(Object.values(result));

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

From JSON/RSS format to an NSDictionary

Is there a library in Objective-C that can automatically convert JSON results into an array of NSDictionary? In simpler terms, a library that can parse the JSON and create an array of NSDictionary filled with the results. ...

Preventing functionality with Jquery hashtag in the URL

My Jquery code successfully shows and hides divs with a button click, but it seems to only work for the first two clicks. After that, a hashtag appears in the URL and the script stops functioning. I attempted to add `e.preventDefault()` at the beginning ...

Grunt Task Unable to Run Modules Referenced with Require in Node Code

I'm facing an issue with my grunt task setup. Here's the code snippet: module.exports = function(grunt) { var info = 'Syncs, updates English translations and downloads Chinese translations.'; grunt.registerTask('t ...

Upon clicking a button on a JSP page, it triggers the ready function in JavaScript. This action may lead to

I have a button placed in my JSP file. <button id="btnViewAll">View All</button> Whenever this button is clicked, I expect the viewAllInventory() function in my JavaScript to be called. function viewAllInventory() { $.ajax({ url : "/Grad ...

Tips for forming JSON object within an array with the help of jQuery

Is there a way to generate JSON Objects using jQuery? I currently have a JSON Object in the following structure: { "1":{ "c_roleid":null, "ObjectID":1, "c_appname":"Default", "c_display":true, "c_add":null, ...

Turn on the text field when the enter key is pressed

I've searched online for solutions, but none of them have resolved my issue. Upon loading my page, I am able to successfully have my JS file select the first textfield. However, I am struggling with getting it to proceed to the next textfield when th ...

Finding it challenging to maintain the alignment of the Drop Down Menu in the center while adjusting the

When I resize my browser or view the page on mobile, the drop-down menu becomes misaligned and extends off the screen. I suspect that adjusting the padding levels might resolve the issue, but previous attempts have only caused more problems. I would appre ...

How can I correctly rotate an object around a specific point using three.js?

Most tutorials/questions about three.js suggest using a parent object to rotate an object around a specific point. This involves creating a parent object at the desired position, attaching the object to it, and then rotating the parent to achieve the desir ...

Encountered an issue while attempting to retrieve the value using Go lang

As a beginner in learning Go Lang programming, I have encountered a challenge with handling data contained in an array. I am in the process of creating a blog using Go Lang and a template, and everything works fine except for appending data from a JSON fil ...

My navbar list elements are not functioning properly due to an issue with JS. Does anyone have a solution to resolve this issue

As I work on creating a website using a free template, I encountered an issue with JS that I am not very familiar with. After conducting some research, it seems like the problem lies within the JS code. Below are the relevant snippets of HTML and JS code: ...

Using PHP and JQuery to disable a button after the letter "U" is typed

I am looking for a way to disable the button when the term "U" (defined as Unable) appears. How can I achieve this? Below is the button in question: <input type="submit" class="form-control btn-warning" name="search" value="Search Data"></input& ...

Troubles arise with Angular's foreach method when attempting to add new elements

Having an angular application integrated with Firebase, I am attempting to update the value of a Firebase item. Whenever the total kilometers change, it should reflect the correct value. Below is the code snippet for my services: countKm(){ this.total ...

Failure to build using the spread operator is unique to the Travis CI environment

I encountered an issue when running the build command npm run build locally for my website. However, on Travis CI, it fails with the following error: > node scripts/build.js /home/travis/build/PatrickDuncan/patrickduncan.github.io/node_modules/@hapi/ho ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

Add Material UI Snackbar to the document's body

I have designed a feature where a component becomes visible only when a user hovers over it. Inside this component, there is a button that allows the user to add something to the local storage. When the button is clicked, the component is removed from the ...

What steps can be taken to optimize and streamline this update API, eliminating redundancy and improving efficiency?

Is there a way to simplify the code in this service method for updating an account on an API? I want to reduce the number of objects within the if conditions. async updateAccount(uuid: string, body: IUpdateAccountDto) { const found = await this.ge ...

Searching by element within a JSON array

I've tried various solutions from different sources but haven't been able to find the correct answer yet. create table mstore ( muuid uuid PRIMARY KEY, msid text, m_json JSONb[] not NULL ); Inserted the first row: insert into mstore (muuid, msid ...

Generating a personalized array by matching an array with an object using JavaScript / Node.js

let obj ={ 97:{ data:"OS", location:"system", access:"globally", parameters:"aed31" }, 490:{ data:"Ae-ds", location:"rootpath", access:"admin rights", parameters:"4fsje" }, 278:{ data:"config", location:"system", ...

How can I populate an array to use in a datatable when rendering?

How can I ensure that my datatable renders with the proper data on my webpage without needing to interact with the sort button? Where should I populate the array for use in a datatable so that it occurs before the rendering? export function MyComponent() ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...