Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data.

const data = this.buildFileTree(dataObject, 0);

The value of dataObject is:

 const dataObject =  JSON.parse(TREE_DATA);

And the content of TREE_DATA is:

const TREE_DATA = JSON.stringify([
{
    Standard: "Food",
    Category: [
      {
        Name: "Vegetable",
        Tables: [
          {
            Description:
              "The carrot is a simple root vegetable, usually conical or cylindrical in shape.",
            Name: "Carrots"
          },
          {
            Description:
              " tomatoes come in a wide variety of shapes: round, oblate, pear-shaped, torpedo-shaped,",
            Name: "Tomatoes"
          }
        ]
      },
      {
        Name: "Fruits",
        Tables: [
          {
            Description: "Oranges",
            Name: "Spherical shape is of orange"
          },
          {
            Description: "Grapes",
            Name:
              "Grapes are typically an ellipsoid shape resembling a prolate spheroid."
          }
        ]
      }
    ]
  }
]);

The buildFileTree function is defined as follows:

buildFileTree(obj: { [key: string]: any }, level: number): FileNode[] {
    return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
      const value = obj[key];
      const node = new FileNode();
      node.filename = key;
      if (value != null) {
        if (typeof value === "object") {
          node.children = this.buildFileTree(value, level);
        } else {
          node.type = value;
        }
      }
      return accumulator.concat(node);
    }, []);
  }
}

The output generated from the function execution is displayed as:

Current Response

Desired Result : Format

It appears that modifications may be necessary in the buildFileTree function. Can someone assist me with this matter?

A live example showcasing the current response can be accessed here: https://stackblitz.com/edit/angular-qsb9c8-x4oaan?file=app%2Ftree-nested-overview-example.ts

Answer №1

To avoid the unnecessary step of converting the array into JSON and then restructuring it, you can directly manipulate the treeData array by looping through each object and organizing the desired data as shown below:

var treeData = [
    {
      Standard: "Technology",
      Subcategories: [
        {
          Type: "Software",
          Products: [
            {
              Description:
                "Operating systems like Windows...",
              Name: "Windows"
            },
            {
              Description:
                "Applications such as Microsoft Office...",
              Name: "Microsoft Office"
            }
          ]
        },
        {
          Type: "Hardware",
          Products: [
            {
              Name: "Laptops",
              Description: "Portable computing devices"
            },
            {
              Name: "Smartphones",
              Description:
                "Mobile phones with advanced features."
            }
          ]
        }
      ]
    }
  ];
  
let structuredData = {};

for (const obj in treeData) {
  const subcat = {};
  treeData[obj].Subcategories.forEach(e => {
    subcat[e.Type] = e.Products.map(i => i.Name)
  });
  structuredData[treeData[obj].Standard] = subcat;
}

console.log(structuredData);


If you need to loop over this structure in a template, you can utilize the following code snippet:

<div *ngFor="let category of structuredData | keyvalue">
    {{ category.key }}
    <ul *ngFor="let subcategory of category.value | keyvalue">
        <li>{{subcategory.key}}</li>
        <ul *ngFor="let product of subcategory.value | keyvalue">
            <li>{{product.value}}</li>
        </ul>
    </ul>
</div>

Answer №2

The issue with your function arises from applying it to a Javascript Object in the example, even though your TREE_DATA is actually a Javascript Array.

If you use the Object.keys() method on an array, it will return the indexes of the elements in the array. For example:

Object.keys([10,20,30]); // returns ['0','1','2']

To correct this, you should adjust your buildFileTree function as shown below:

// Create a new JavaScript object where each key represents a 'Standard' entry and its value
// is another object containing 'Category.Name' as the key and an array of all entries' Names as the value 

const result = dataObject.reduce((acc1, e1) => {
  acc1[e1.Standard] = e1.Category.reduce((acc2, e2) => {
    acc2[e2.Name] = e2.Tables.map(e => e.Name);
    return acc2;
  }, {})
  return acc1;
}, {});

I hope this clarifies things for you! If you're not familiar with the reduce and map methods, I recommend looking into them!

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

Display a div using Jquery when hovering over it with several classes

I want to create a hover effect where div2 fades in slowly when hovering over div1 within the same container. However, my jQuery code doesn't seem to be working as expected... $(".div").hover(function() { $(this).find(".div2").animate({ opac ...

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 ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

Looking to incorporate Slick Carousel as the main slider on my website for a dynamic hero section using JavaScript

Currently in the process of expanding my knowledge in javascript, I am now delving into setting up Slick Carousel. It is essential that it functions as a hero slider on my website. If you are interested in checking out Slick Carousel on github, feel free ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

What methods can be used to disable a JavaScript function, such as utilizing hasClass()?

I am currently customizing a WordPress theme to load posts and pages using AJAX. I have successfully implemented this functionality with the code snippet below, but now I need to prevent the AJAX function from running when clicking on the logo that links t ...

`Node.js encountering issues with undefined JSON Array values`

I am facing an issue while trying to extract an array of strings from a JSON file. Although I am able to successfully load the JSON array, I am encountering difficulties in accessing the actual data within it. The structure of my JSON file is as follows: ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

Access real-time information via JSON

I am facing a logical thinking challenge. Successfully retrieving data from a PHP file via JSON, but now encountering a slight issue. My goal is to retrieve various headlines - main and sub headlines. Each main headline may contain an unknown number of su ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Exploring numpy array elements, identifying pairs, and strategies for addressing boundaries/corners

I'm struggling to develop a function below, unsure of the proper execution. Imagine having a 2D numpy array like import numpy as np arr = np.array([[ 1, 2, 3, 4], [ 1, 6, 7, 8], [ 1, 1, 1, 12], [13, 3, 15, 16]]) This matrix is 4x4 and appe ...

Looking for a way to locate the point where objects intersect in three.js?

My goal is to load 20 objects with random positions in a way that they do not intersect. How can I detect and check for intersections between these objects? for (var i = 0; i < 20; i++) { // Create a material var textureLoader = new ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

How can a row in AG-Grid be updated without causing a refresh?

I am working on adding a custom radio button feature for users to select a row. Currently, I have the following code: const Cell = (cellProps) => { const { data, node, api } = cellProps const selectedRow = () => { let { isChecked } = data ...

504 error when attempting to access HTTPS with Node.js

I have encountered an issue with making an https request in my backend node.js web app. The code I am using is as follows: const express = require('express'); const https = require('https'); const app = express(); app.get("/", functio ...

What measures can be taken to restrict users from inputting decimal values?

My website includes an order page where users can input quantities for various items. While some items allow for decimal quantities, others do not. What is the most effective method to restrict users from entering decimal quantities? (Besides using an ale ...

Require assistance with displaying a menu on a website using JQuery

Is there a way to create a menu similar to the one shown in the image below?https://i.sstatic.net/QxNPL.png To learn more about this menu, you can visit their website by clicking on this Link. I have copied some code (HTML code and links to CSS and .js fi ...