Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title.

Below is the JavaScript code:

var phonecatApp = angular.module('myApp', [])
phonecatApp.controller('myController', function myController($scope, $http) {
  $http.get('https://api.zotero.org/users/475425/collections/9KH9TNSJ/items?format=json')
    .then(function (response) {
      var data = response.data

      data = data.filter(function (obj) {
          return true
        })
        .map(function (obj) {
          return {
            key: obj.key,
            parentItem: obj.data.parentItem,
            title: obj.data.title
          }
        })

      var log = []
      var parent = angular.forEach(data, function (value, key) {
        if (value.parentItem === undefined) {
          this.push(value)
        }
      }, log)
      $scope.paR = log

      var nlog = []
      var children = angular.forEach(data, function (value, key) {
        if (value.parentItem !== undefined) {
          this.push(value)
        }
      }, nlog)
      $scope.chilD = nlog
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>Hello</title>
  <link href=" css/bootstrap.min.css " type="text/css " rel="stylesheet ">
  <link href="themes/default/style.min.css " type="text/css " rel="stylesheet ">
  <link href="css/angular-json-human.min.css" type="text/css" rel="stylesheet">
</head>

<body ng-controller="myController ">
  <div>
    <ul ng-repeat="myJ in paR">
      <li>
        <h3>{{myJ.key}}</h3></li>
      <li>{{myJ.title}}</li>
    </ul>
    <ul ng-repeat="myN in chilD">
        <li>
          <h3 style="color:red">{{myN.key}}</h3></li>
        <li>{{myN.title}}</li>
      </ul>
  </div>

  <script src="js/angular.min.js "></script>
  <script src="js/jquery-1.12.4.min.js "></script>
  <script src="js/bootstrap.min.js "></script>
  <script src="js/npm.js "></script>
  <script src="js/jstree.min.js "></script>
  <script src="tree.js "></script>
</body>

</html>

My JSON items can either be parents or children. Need assistance on displaying them in a tree format with respect to parent-child hierarchy following the nLogn rule.

Answer №1

If you're looking for an effective directive to use, consider checking out the angular treeview module.

It works with JSON data structured like this:

$scope.treedata = 
[
    { "label" : "User", "id" : "role1", "children" : [
        { "label" : "subUser1", "id" : "role11", "children" : [] },
        { "label" : "subUser2", "id" : "role12", "children" : [
            { "label" : "subUser2-1", "id" : "role121", "children" : [
                { "label" : "subUser2-1-1", "id" : "role1211", "children" : [] },
                { "label" : "subUser2-1-2", "id" : "role1212", "children" : [] }
            ]}
        ]}
    ]},
    { "label" : "Admin", "id" : "role2", "children" : [] },
    { "label" : "Guest", "id" : "role3", "children" : [] }
];   

You can see how it will look when displayed

Just make sure to format your data accordingly before implementing it.

Answer №2

this is the answer !!!!

var phonecatApp = angular.module('myApp', [])
phonecatApp.controller('myController', function myController($scope, $http) {
  $http.get('https://api.zotero.org/users/475425/collections/9KH9TNSJ/items?format=json')
    .then(function(response) {
      var data = response.data

      data = data.filter(function(obj) {
          return true
        })
        .map(function(obj) {
          return {
            key: obj.key,
            parentItem: obj.data.parentItem,
            title: obj.data.title
          }
        })
      console.log(data)

      $scope.getParentData = function() {
        var log = []

        angular.forEach(data, function(value, key) {
          if (value.parentItem === undefined) {
            this.push(value)
          }
        }, log)
        return log
        console.log(log)
      }

      $scope.getChilds = function(p) {
        var log = []

        angular.forEach(data, function(value, key) {
          if (!value.parentItem || value.parentItem !== p.key) {
            return
          }
          this.push(value)
        }, log)
        return log
        console.log(log)
      }
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>nested tree</title>
</head>

<body ng-controller="myController" class="container">

  <ul>
    <li ng-repeat="myPar in getParentData()">
      <h4>{{myPar.title}}</h4>
      <ul>
        <li ng-repeat="myChild in getChilds(myPar)">
          <p>{{myChild.title}}</p>
        </li>
      </ul>
    </li>
  </ul>
</body>

</html>

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

Is there a way to retrieve information from "nested" JSON files using gruntjs?

If we have a Gruntfile with pkg: grunt.file.readJSON('package.json') and inside the package.json file there is an object like this: { "file": "data.json" } How can we access the information from data.json? It might contain details such as: { ...

produce in the element that is invoked within an each function

This snippet is a key part of my component's template: {{#each displayResults}} <li {{action addSelection this}} {{bindAttr class=\":result active\"}}> {{#if controller.template}} {{yield}} {{else}} <span class=\ ...

Employing data retrieved from an ajax response as a json object

As a newcomer to ajax and Jquery, I am attempting to display my database graphically using c3.js. However, I am facing challenges with utilizing my ajax response in a JavaScript variable. Below is the JSON response from response.php: [{"time":"2014-05-20 ...

What is preventing me from reading the input value in AngularJS using jQuery?

Just starting out with angularjs and I need help with this code sample: <ng-input theme='fumi' id='txtEmail' label='Email Address' icon='icon icon--fumi mdi mdi-select-all' style="font-size:medium;width:40%;"&g ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Redirecting in Next.js from an API route

I am in the process of developing a backend application that necessitates user authentication. Within this project, I'm utilizing 2 external APIs: API A: responsible for managing user accounts and sessions API B: utilized for executing CRUD operation ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

Integrate a fully developed ReactJS 16.x application seamlessly into an existing AngularJS 1.x framework

On a current project I'm working on, there's a unique challenge where I need to incorporate a compiled ReactJS app into an existing AngularJS project, with the Chrome/Firefox browser serving as the end-user interface. This setup isn't ideal, ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

JavaScript Array failing to transfer to PHP using AJAX

I've encountered a recurring issue with my code and despite searching for solutions, I can't seem to find one that works for me. The problem lies in trying to delete a specific row from a table based on whether the user selects a checkbox associa ...

Utilizing a Spring Kafka listener to consume JSON data and automatically determine the corresponding domain object

I have a project where I need to process various types of JSON messages that will be published. Unfortunately, I cannot modify the publisher's code to include any headers. However, I am interested in utilizing @KafkaHandler to manage these different J ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Transform information into a json structure

import enum import requests from bs4 import BeautifulSoup import json import pandas as pd headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3" ...

Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library. My website features several cards, and my goal is to showcase a spinner during the image loadin ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

Is it possible to extract a div from a third-party domain and showcase it on my website?

Trying to integrate content from my Veetle.com channel onto my personal website has proven to be quite the challenge. Initially, I attempted to modify an iframe with CSS to display only the schedule information, but encountered limitations due to using 3rd ...

How can I set the default option of a dropdown menu to "Choose an option"?

When setting up my dropdown menu, the default option is blank. Is there a way to change this text to something else? <body ng-controller="controller"> <span>Options: </span> <select ng-options="item as ...