Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array within the same object.

The desired result should look like this:

[{"title":"title of category","sub":[array of related sub]} , ...]

Here is a snippet of my code:

  public data = SERVERRESPONE;
  public categories = [];

      this.data.filter(c => c.parent_id === null).map(c => <{ title: {}; subcategories: {} }>{
        title: {"title":c.title},
        subcategories: this.data.filter(sc => sc.parent_id === c.cat_id).map(sc => sc.title)
      }).forEach(c => {
        this.categories.push([c.title, [c.subcategories]]);
      });

This is an example of the server response:

[
        {
            "id": 5,
            "cat_id": 0,
            "parent_id": null,
            "title": "web development"
        },
        {
            "id": 6,
            "cat_id": 1,
            "parent_id": null,
            "title": "android development"
        },
        {
            "id": 7,
            "cat_id": null,
            "parent_id": 0,
            "title": "php"
        },
        {
            "id": 8,
            "cat_id": null,
            "parent_id": 1,
            "title": "java"
        }
    ]

Answer №1

This question is quite interesting, but the solution is surprisingly simple!

const data = [
    {
        "id": 5,
        "cat_id": 0,
        "parent_id": null,
        "title": "web development"
    },
    {
        "id": 6,
        "cat_id": 1,
        "parent_id": null,
        "title": "android development"
    },
    {
        "id": 7,
        "cat_id": null,
        "parent_id": 0,
        "title": "php"
    },
    {
        "id": 8,
        "cat_id": null,
        "parent_id": 1,
        "title": "java"
    }
]

let result = []

for (let item of data) {

    if (item.parent_id === null) {
        let new_item = item,
            subitems = []

        for (let iterator of data) 
            if (iterator.parent_id === item.cat_id)
                subitems.push(iterator)

        new_item.subitems = subitems
        result.push(new_item)
    }

}

console.log(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

Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong? Here is ...

What is the method to create all possible combinations from the keys of a JSON object?

How can I generate object B that includes all combinations of object A using a key-value pair? { "x": "data-x", "y": "data-y", "z": "data-z" } The desired output should look like this: { ...

Transforming precise military time using Angular and Javascript filtering

There are a few times where I find myself liking 01:45 //and 15:00 I believe this time format is HH:MM in military time? While I have come across some advanced functions that can parse sentences and even include seconds like HH:MM:SS, I am looking for a ...

I require the parsing and storage of a list of values from either a JSON or YAML file

To extract specific values from a yaml or json file, the following example demonstrates how to do so. The content below is from a sample yaml file: swagger: '2.0' info: description: >- This is a sample server Petstore server. You can fi ...

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

Slicing an array in Javascript/Angular before it is officially initialized

Is it possible to specify the portion of an array to retrieve before making a $http GET request in Angular? I am aware of slicing arrays, but wondering if I can set this up in advance for better performance. In PHP, you can do something similar, but not ...

Tips for implementing react portal functionality in react 15

Working on my current project with react 15, I am looking to display an overlay on the screen when a dropdown is opened. While React 16 allows us to utilize React portal to render children into a DOM node outside of the parent component's hierarchy, h ...

Using the $.ajax function with the PUT method and sending an OPTIONS request

Here is my code snippet: function test(segmentId) { var url = "http://...../api/avoidsegments/123456"; $.ajax({ url: url, type: "PUT", contentType: "application/json", data : { "appID": ig_appID, ...

Determine the difference between a CSS selector string and an XPath string

Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector) function that can handle both css selectors and XPath selectors in string form. My dilemma lies in determining whether a given ...

Getting specific information from a JSON URL can be achieved by utilizing tools like JavaScript

Looking for a solution to extract specific data from JSON file? Here is the JSON Data available in PHP url named house.php: { "Error": "", "ErrorCode": 0, "Guid": "", "Id": 0, "Success": true, "Value": [ { "MAIN": 225, "PHASE": 219418523, "G": "7TH Divisi ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

https://i.sstatic.net/FTMz7.png Why is React only displaying an empty screen instead of showing errors like on my instructor's system? https://i.sstatic.net/QCbgG.png How can I resolve this issue? EDIT: While I can see the error in the console and ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

looking to get into deeper levels of JSON data with json.load

I have implemented Hufman's Honeywell Python code to extract data from the MyTotalConnectComfort website. The code can be accessed here. I made adjustments to the code for compatibility with version 2.7 and integrated Flask into the process. Upon cal ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

How can you use Pandas groupby with a list of columns that have identical categories?

Essentially, my goal is to transform the following: Date 0 1 2 0 10-1 thing1 None None 1 10-1 thing1 thing1 None 2 10-2 thing2 thing1 None 3 10-3 thing1 thing1 thing2 into a grouped dataframe as shown belo ...

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

What is the best way to showcase a firebase "row" containing two columns within an Ionic 2 application?

Currently in the process of developing an app to keep track of assignments using Ionic 2/Typescript and Firebase as the backend database. The main page displays a list of assignments retrieved from the database. Creating a new assignment requires the user ...

Remove an element from an array based on the index provided by the front end

Currently, I am attempting to eliminate a specific item from a PHP array stored in a JSON file. Here is an example of the JSON file structure: { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ " ...

Utilizing Firebase objects across multiple files: A comprehensive guide

I apologize for my ignorance, but as I am teaching myself, I have not been able to find the answer in the available documentation. My current project involves developing a Vue application with Firebase as the backend. To utilize Firebase services, you mus ...