Enhanced hierarchical organization of trees

I came across this code snippet:

class Category {
  constructor(
     readonly _title: string,
  ) { }

  get title() {
    return this._title
  }
}

const categories = {
  get pets() {
    const pets = new Category('Pets')

    return {
      get dishes() {
        const dishes = new Category('Dishes')

        return dishes
      }
    }
  },
  get cloth() {
    const cloth = new Category('Cloth')

    return {
      get accessories() {
        const accessories = new Category('Accessories')

        return accessories
      }
    }
  }
}

I would like to use it in this manner:

const product = new Product(categories.pets.dishes)

While this approach is useful, I need to display it as a tree structure on the frontend:

<ul>
  {Object.entries(categories).map(
    ([slug, category]) => {
      return (
        <React.Fragment key={slug}>
          <li>{category.title}</li> // encountering an issue here
            <ul>
              {Object.entries(category).map(([s, c]) => {
                return <li key={s}>{c.title}</li>
              })}
            </ul>
         </React.Fragment>
       )
  })}
</ul>

How can I retrieve the name of the parent category? What would be the most effective way to structure and handle this scenario?

Answer №1

The primary issue lies in the categories.pets section where you instantiate the pets object but fail to utilize it further. This leads to its disappearance without fulfilling any purpose. Instead of this, you create a new object using an object literal (which is not an instance of Category) and return that object. As expected, this new object lacks a title property...

To resolve this, include the dishes getter within the existing pets object like this:

  get pets() {
    const pets = new Category('Pets');
    
    Object.defineProperty(pets, "dishes", {
      get() {
        const dishes = new Category('Dishes');
        return dishes
      },
      enumerable: true,
      configurable: true,
    });
    
    return pets;
  },

Extend the same correction to the second getter as well.

Furthermore, while iterating through the JSX code's inner loop, ensure to exclude the _title property from processing. To achieve this, consider updating the Category class to use a private field

#title</code or alternatively filter out properties starting with an underscore during iteration. You can do so by utilizing the <code>.filter
method:

              {Object.entries(category).filter(([s]) => s[0] !== "_")
                                       .map(([s, c]) => {
                return <li key={s}>{c.title}</li>
              })}

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

When the button is pressed, the TypeScript observable function will return a value

Check out the snippet of code I'm working with: removeAlert() : Observable<boolean> { Swal.fire({ title: 'delete this file ?', text: 'sth', icon: 'warning', showCancelButton: true, ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

retrieving information from server via ajax to display on chart

I am currently utilizing the jqPlot JavaScript library for generating graphs and charts in one of my applications, which can be found at . Within my application, there are approximately 5-6 pages where I have integrated this library. However, I would like ...

Differences in weekend start and end days vary across cultures

Looking for a solution to determine the weekend days per culture code in Typescript/Javascript? While most countries have weekends on Sat-Sun, there are exceptions like Mexico (only Sunday) and some middle-eastern countries (Fri-Sat). It would be helpful ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

The Vue component fails to refresh after modifications to the state in the Pinia store

I'm currently immersed in my inaugural vue application, focusing on constructing the login functionalities. To handle State management, I've implemented pinia. I've set up a Pinia Store to globally manage the "isLoggedIn" state. import { def ...

Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I ...

Re-sorting with _.sortBy() eliminates additional 0s from decimal values (transforming 0.10 to 0.1 and beyond)

Here is an array that needs to be sorted: var baseBetAmount = [ { val: 'OtherBaseBet', text: 'Other' }, { val: 0.10, text: '$0.10' }, { val: 0.20, text: '$0.20' }, { val: 0.50, text: ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

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

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

What is the mechanism behind $scope.$on activation and $destroy invocation?

Seeking an explanation on the functionality of $scope.$on and how $destroy works in two separate controllers. When switching routes, a new controller is invoked, leading to the activation of $destroy. Could someone shed some light on how $interval is in ...

Is the error message "not a function" appearing when calling a function from a parent to a child?

I am trying to understand parent-child relations in React as I am new to it. In my understanding, the following scenario should work: I have a parent component called <Home/> and within it, there is a child component called <ProjectDialog>, wh ...

Displaying a distinct image for each Marker when hovering over them on a Map

I have implemented ReactMapGL as my Map component and I am using its HTMLOverlay feature to display a full-screen popup when hovering over markers. However, even though I have set different image data for each marker, all of them show the same image when h ...

When making an Ajax request to a controller, rather than simply returning JSON data, it redirects you to a

Utilizing jQuery and MVC 5, I have implemented a modal form in my project. Upon clicking 'ok' on the modal box, the javascript function should trigger an ajax call to the "Companies/Createa" controller. The code successfully executes and update ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...