2

I have a nested json array of objects as below. I wanted to parse so that I can read using ng-repeat and display in the html table. In the table, names will become headers and values become cells in each row. can you please help me as how to do this in angularjs ?

[
    {   
        "records": 
        [
            {
                "cells": [
                    {"id": "102", "value": "John"},
                    {"id": "101", "value": "222"},
                    {"id": "103", "value": "600987"}
                ]
            },
            {
                "cells": [
                    {"id": "103", "value": "69987"},
                    {"id": "101", "value": "999"},
                    {"id": "102", "value": "Susan"}
                ]
            }
        ],
        "headers": [
            {
                "id": "101",
                "name": "emp_id"
            },
            {
                "id": "102",
                "name": "emp_name"
            },
            {
                "id": "103",
                "name": "emp_salary"
            }
         ]
     } 
 ]

2 Answers 2

4

Here is your table should be like this:

<table>
  <tr>
    <th ng-repeat="h in list[0].headers">{{h.name}}</th>
  </tr>
  <tr ng-repeat="record in list[0].records">
    <th ng-repeat="cell in record.cells">{{cell.value}}</th>
  </tr>
</table>

See a working plunkr https://plnkr.co/edit/MyUaovStvxj58RIy0CW7?p=preview

Update:

And you can use orderBy with ng-repeat as davidkonrad mentioned:

<table>
  <tr>
    <th ng-repeat="h in list[0].headers | orderBy: 'id'">{{h.name}}</th>
  </tr>
  <tr ng-repeat="record in list[0].records">
    <th ng-repeat="cell in record.cells | orderBy: 'id'">{{cell.value}}</th>
  </tr>
</table>
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Joe! Thanks so much for the quick reply. Solution works fine if the records are ordered. In my problem, i have unordered array, I have re-edited my question and sorry for not putting up right question at first. can you tell me what can be done in such scenario?
@sai123 use ng-repeat="h in list[0].headers | orderBy: 'id' " and the same with records.
Thanks Joe! Awesome! Works Perfectly fine.
0

Adding something extra to Joe's answer. If you are planning to get the data from a separate JSON file, you can use the following code in your .js file.

(function () {
  'use strict';

  angular.module('plunker', [])
  .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope', '$http'];
  function MainCtrl($scope, $http) {
    $http.get('[path to your JSON file]/data.json').success(function (data) {
      $scope.list= data;
    });
  }
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.