display the array of objects according to their level

I am looking to display a nested list with proper indentation based on the level of each object in an array.

Each object is assigned a level, ranging from 0 to 2 where 0 represents the top level and 2 represents the innermost level. The desired output should include indentation to indicate the hierarchy of levels in the list.

An example of the expected list format:

0
    1
    1
         2
         2

The current code implementation is as follows:

for (let category of json.categories) {
  if ((category.level = 0)) {
    console.log(
      category.category + "https://www.example.com/" + category.seo_name
    );
  }

  else if ((category.level = 1)) {
    console.log(
      "   " +
        category.category +
        " " +
        "https://www.example.com/" +
        category.seo_name
    );
  }

 else if ((category.level = 2)) {
    console.log(
      "     " +
        category.category +
        " " +
        "https://www.example.com/" +
        category.seo_name
    );
  }
}

This code snippet is not only cumbersome but also ineffective as it fails to produce the intended indentation in the output.

Here is an example of the data structure:

const json = {
  categories: [
    {
      category_id: "198",
      category: "Appliances",
      seo_name: "appliances",
      level:0
    },
    {
      category_id: "184",
      category: "Industrial Appliances",
      seo_name: "industrial-appliances",
      level:1
    },
  ],
  params: {
    visible: false,
    sort_order: "asc",
  },
};

Answer №1

One way to format this code is by utilizing the PRE tag and adjusting the spacing based on the level specified in a previous suggestion


    const obj = { 
      categories: [ 
        { category_id: "198", category: "Appliances", seo_name: "appliances", level: 0 }, 
        { category_id: "184", category: "Industrial Appliances", seo_name: "industrial-appliances", level: 1 },
        { category_id: "187", category: "Appliances", seo_name: "appliances", level: 2 }
      ], 
      params: { 
        visible: false, sort_order: "asc",
      } 
    };

    const container = document.querySelector('pre');
    container.innerHTML = obj.categories
      .map(({level, category, seo_name}) => `${"".padStart(level, "\t")}${category} https://www.example.com/${seo_name}`)
      .join("\n")
    
<pre></pre>

Answer №2

var values = [{ grade: 50 }, { grade: 60 }, { grade: 70 }, { grade: 80 }, { grade: 90 }];

for (let item of values) {
  let result = "";
  result = ' '.repeat(item.grade * 5) + item.grade;
  console.log(result)
}

If you prefer a more concise syntax.

var values = [{ grade: 50 }, { grade: 60 }, { grade: 70 }, { grade: 80 }, { grade: 90 }];

values.forEach(item => console.log(' '.repeat(item.grade * 5) + item.grade))

Answer №3

Make sure to use == instead of = when assigning values within your if condition. You might find it cleaner to utilize a switch statement rather than multiple if statements, especially in this scenario. Additionally, consider implementing a loop to easily adjust the number of spaces for indentation as needed, eliminating the need for manual counting.

var data = [{ level: 0 }, { level: 1 }, { level: 1 }, { level: 2 }, { level: 2 }];

for (let element of data) {
  let result = "";
  switch (element.level) {
    case 1:
      for (let index = 0; index < 4; index++)
        result += " ";
      result += element.level;
      break;
    case 2:
      for (let index = 0; index < 8; index++)
        result += " ";
      result += element.level;
      break;
    default:
      result += element.level;
  }
  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

React Native: Issue with TextInput vanishing within View container

Currently, I am diving into the world of React Native by following along with a book that teaches how to create a to-do app. However, my progress has hit a roadblock due to an error/bug I encountered on IOS (not sure if it also affects Android since I have ...

I don't understand why I keep encountering a "segmentation fault 11" even though I have allocated sufficient memory

I am working on a double pointer char array to store strings, implementing an append function. The goal is to add a provided string to the end of the array while keeping track of the number of elements using num_strings pointer. However, I am facing an iss ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

Strip all textual content from within HTML div elements while retaining the original HTML tags and formatting

I currently have the following HTML code: <div> Here <a href="#"> is </a> <p> Text, that I want to </p> be removed </div> This is what I desire: <div> <a href="#"> </a> <p& ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

Integrate a PHP variable into an HTML/JavaScript statement that was previously transformed from PHP

Incorporated within this PHP variable is a mix of HTML and JavaScript code. My task is to enhance it by adding another PHP variable. Specifically, I have a PHP variable denoted as $user->user_email. How can I seamlessly integrate this variable into th ...

Experiencing complications when retrieving API information in my React component

There is a json file available: {"area":[{"id":"1","name":"abc","address":"223 "},{"id":"2","name":"xyz","address":"123 "}] I am trying to fetch and display the data in my component using react and redux. Although I have successfully loaded the url with ...

The module @vue/cli-plugin-unit-jest is expected to contain a file named "jest-preset.js" or "jest-preset.json" at its root

My project setup consists of a single folder containing only icons. I used the command vue create . For testing, I decided to go with Jest and didn't make any additional configurations. When I try to run npm run test:unit, I encounter the following e ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Encountering a 'Object is not a function' issue while attempting to implement Page Object with Protractor

Whenever I attempt to run my tests, I keep encountering a TypeError: object is not a function. Prior to incorporating PageObject, everything worked fine. Below is my spec.js 'use strict'; var todoAppPage = require('../pages/angular.page&a ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...

Extracting ng-template Content into a Variable from the Source

I am trying to save the contents of my template into a variable. Here is how my current code looks: HTML <script type="text/ng-template" id="a.html" src="templates/a.html"></script> JS vm.template = $templateCache.get('a.html'); c ...

Using JavaScript to access the Skyscanner API yielded a response with the error message indicating that the 'Access-Control-Allow-Origin' header was missing

After implementing the Skyscanner Api to create a session, I received a 201 response indicating that the session was successfully created. However, my script encountered an exception which halted its execution: "No 'Access-Control-Allow-Origin' h ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Is there a way for me to manually initiate a digest cycle on the parent scope based on my instructions?

I am struggling with getting a directive to render automatically when a change is made to the underlying model programmatically. Using $scope.$apply seems like the right approach, but unfortunately it's not working as expected. The directive only rend ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

What is the process for removing globally declared types in TypeScript definitions?

There are numerous libraries that cater to various platforms such as the web, Node servers, and mobile apps like React Native. This means they can be integrated using <script /> tags, require() calls, or the modern import keyword, particularly with t ...

Extracting the text that is displayed on a specific element

I have a very simple question that I can't seem to find an answer for due to the lack of documentation on the javascript bindings of selenium-webdriver. While there is ample documentation for the java bindings, the same cannot be said for javascript. ...

Merge individual character arrays into a multidimensional array

I've defined several arrays as follows: char array1[10] = "Nick"; char array2[10] = "Tomas"; char array3[10] = "Nathan"; char array4[10] = "John"; char array5[10] = "Paul"; char *new_array[3][1]; My goal is to construct a new table like this: Nick ...