Retrieving data from nested JSON by leveraging distinct fields with AngularJS

Here is a sample json data:

{  
   "id":14,
   "discussion":8,
   "parent":0,
   "userid":2,
   "subject":"communication skill discussion 2",
   "message":"<p>hi all to communication discussion 2 </p>",
   "children":[  
      24,
      16,
      15
   ]
},
{  
   "id":15,
   "discussion":8,
   "parent":14,
   "userid":2,
   "subject":"Re: communication skill discussion 2",
   "message":"<p>hiiiiiiiiii</p>",
   "children":[  
      25,
      23
   ],
},
{  
   "id":23,
   "discussion":8,
   "parent":15,
   "userid":2,
   "created":1461562317,
   "modified":1461562317,
   "mailed":0,
   "subject":"Re: communication skill discussion 2",
   "message":"<p>helloooo</p>",
   "children":[  

   ],
}

I need assistance in looping through the json data using ng-repeat in angular. I want to start by fetching details of elements whose IDs correspond to the values in the children array. For example, for id:14, I want to retrieve details of id:15 since it's one of its children. Then continue to the next level of children if available, until we reach an element with no children and print its message.

Can you provide guidance on how to achieve this using ng-repeat in Angular?

Answer №1

View the live demo.

Here is the code snippet:

HTML:

<div ng-app="app" ng-controller="test">
  <div ng-repeat="(key,value) in data">
    {{key + 1}}) --
    <span ng-if="value.children.length > 0">
    {{value.children}}
    </span>
    <span ng-if="!(value.children.length > 0)">
    No children found!!
    </span>
  </div>
</div>

JS:

var app = angular.module('app', []);

app.controller('test', function($scope) {
  $scope.data = [{
    "id": 14,
    "discussion": 8,
    "parent": 0,
    "userid": 2,
    "subject": "communication skill discussion 2",
    "message": "<p>hi all to communication discussion 2 </p>",
    "children": [
      24,
      16,
      15
    ]
  }, {
    "id": 15,
    "discussion": 8,
    "parent": 14,
    "userid": 2,
    "subject": "Re: communication skill discussion 2",
    "message": "<p>hiiiiiiiiii</p>",
    "children": [
      25,
      23
    ],
  }, {
    "id": 23,
    "discussion": 8,
    "parent": 15,
    "userid": 2,
    "created": 1461562317,
    "modified": 1461562317,
    "mailed": 0,
    "subject": "Re: communication skill discussion 2",
    "message": "<p>helloooo</p>",
    "children": [

    ],
  }];
});

UPDATE: Following the request

Live Demo

HTML:

<div ng-app="app" ng-controller="test">
  <div ng-repeat="(key,value) in data">
    [{{key + 1}}] --
    <div ng-if="value.children.length > 0">
      <div ng-repeat="item in value.children">
        <span>{{item}}</span> <span class="green" ng-bind-html="getMessage(item)"></span>
      </div>

    </div>
    <span ng-if="!(value.children.length > 0)">
    No children found!!
    </span>
    <br />
  </div>
</div>

JS:

  $scope.getMessage = function(itemId) {
    var flag = true;
    var msg;
    angular.forEach($scope.data, function(value, key) {
      if (flag && value.id == itemId) {
        flag = false;
        msg = value.message;
      } 
    });
    return $sce.trustAsHtml(msg);
  }

CSS:

.green {
  color: green;
}

Answer №2

Utilize the ng-repeat directive for rendering the data entries.

<ul ng:controller="Cntl">
<li ng:repeat="item in data">
    {{item.subject}}: Main
    <ul>
        <li ng:repeat="child in item.children">{{child}} : Descendants
        </li>
    </ul>
</li>

This is just one method for displaying content on a webpage using html. The appearance of the ng-repeat may vary depending on your design preferences.

Answer №3

If you want to filter data, you have the option of using either lodash or underscore with their _.where method:

<div ng:controller="Cntl">
  <div ng:repeat="item in data">
   {{item.subject}}<br/>
    Children
    <div ng:repeat="child in item.children">{{_.where(data, {id:child});}}
    </div>
 </div>

Answer №4

To begin, it's essential to reformat your json data into a tree-like structure. You may find helpful information in this resource. Next, you'll need to iteratively incorporate templates in a recursive manner.

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

Ensuring the consistency of form fields using AngularJS

Using Angular 1.5.11 I am currently working on an HTML form that contains multiple fields, such as : <div ng-app="validationApp" ng-controller="mainController"> <div class="container"> <div class="ro ...

Exploring the process of loading a new page in the browser through nodeJS

I'm a beginner looking to load a new page in the browser with just a button click. I've tried some code, but it's not working as expected. Here's what I have: NodeJS file: var http = require('http'); var fs= require('fs ...

What causes the difference between object[key] and Object.key in JavaScript?

After running the following code snippet, I observed that "typeof object[key]" is displaying as a number while "typeof object.key" is showing undefined. Can anyone explain why this unusual behavior is occurring? var object = {a:3,b:4}; for (var key in o ...

Access information from a service

I have developed a new service named servcises/employees.js: angular.module('dashyAppApp') .service('employees', function () { this.getEmployees = function() { return $.get( '/data/employee.json' ); }; }); ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Encountering a Null Pointer Exception while working with List Adapter and Custom List View in Android Studio

I've been working on developing an app in Android Studio that involves parsing a JSON document and displaying two TextViews of data for each instance - Signal and Noise. I'm attempting to create a custom list view to potentially add more detail t ...

AngularJS $q.all resolves only after the pre-flight request is successfully completed via the OPTIONS request

There seems to be a technical hurdle in handling multiple delete requests that are preceded by an OPTIONS pre-flight request. The issue arises when the control flow reaches the then block of $q.all following the OPTIONS request. Below is the code snippet: ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

How to store lengthy JSON strings in SAP ABAP as variables or literals without extensive formatting restrictions

Is there a way to input lengthy JSON data into ABAP as a string literal without the need for excessive line breaks or formatting? Perhaps enclosing the string in a specific template, or utilizing a method similar to JSON.stringify(..) found in other langua ...

Selenium WebDriverJs has difficulty in setting up a new client for iOS devices

Struggling to make Selenium WebDriverJS work with the iOS browser, but unfortunately facing some issues. I followed the instructions on setting up the "iWebDriver" project as mentioned on the iPhoneDriver wiki page. The Python script worked fine, and even ...

What is the method for generating a random Vector3 inside a sphere?

Recently, I've been experimenting with creating a random point within a sphere. However, I seem to be struggling in getting it right. The current code I have written actually returns a point within a cube instead of a sphere. I suspect there might be ...

Utilize discord.js to create commands with multiple arguments

I'm currently working on creating a command with multiple arguments, like this example: !Poll "This is the title" "This is the description" "This is the time" However, I've encountered an issue where it only recognizes the first 2 arguments. ht ...

What is the best way to retrieve all key-value pairs of PDF form fields using JavaScript in Acrobat?

I've been on the hunt for a code snippet that can retrieve values for specific fields in a PDF using JavaScript within Acrobat. However, my goal is to capture all fields as key-value pairs in JavaScript. I did try some existing code, but unfortunatel ...

The deployment of the next.js error on Vercel was successful ✓ All five static pages were generated without any issues. However, there was an error encountered during the export process specifically in the

I'm having trouble deploying a next.js + mongodb project to Vercel. Every time I try, I encounter this error: Error occurred prerendering page "/products". Read more: https://nextjs.org/docs/messages/prerender-error SyntaxError: Unexpected t ...

Javascript's most frequent appearance

My knowledge of JavaScript is quite limited and basic. Essentially, I am trying to create a pop-up that displays the answer based on the values entered. The issue I'm encountering with the code below is that when I input an array like 1,2,3,2, the out ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

AngularJS design pattern for creating user profiles with both public and private visibility options

Within the platform I am developing, there exists the ability to follow or unfollow other users. Additionally, users have the option to edit their own profiles when accessed. Currently, my code includes one state, /profile/:id, which displays the user prof ...

Error encountered while waiting for Angular to finish loading in Protractor: ScriptTimeoutError - Task: Protractor.waitForAngular()

Yesterday went smoothly, but today after updating to pull all commits from svn, everything stopped working. Every time I run a test, I encounter this error: ScriptTimeoutError: script timeout And: From: Task: Protractor.waitForAngular() - Locator: By(c ...

Navigating within an ionic framework

I am facing an issue with a simple form in my application. When I try to enter user details, the Android keyboard hides the email field and mobile number field, making it impossible for me to scroll the page upwards. Can anyone suggest a solution? <i ...