Priya
Priya

Reputation: 591

Change array of json to a table in angularjs

My json looks like this :

[{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}]

I want a table in angularjs similar to this

Name Age Gender
A     20   M
B     30   M
C     40   F

I could see many example when my json is similar to this :

[
    {Name: "A",     Age: "20",  Gender: "M"},
    {Name: "Bag",   Age: "30", Gender: "F"},
    {Name: "Pen",   Age: "40",  Gender: "F"}
];

But I don't know how to proceed with my json. Could anyone help with this?

Upvotes: 1

Views: 140

Answers (3)

num8er
num8er

Reputation: 19372

Use lodash _.zip function to arrange them in array, and _.map to convert it to json objects using custom function:

var rows = _.zip(users.Name, users.Age, users.Gender);  // [["A",20,"M"],...]
$scope.users = 
    _.map(rows, function(row) {
        return {Name: row[0], Age: row[1], Gender: row[2]}
    });

and then iterate them getting values:

<table ng-controller="UsersTableController">
    <thead>
        <th>NAME</th>
        <th>AGE</th>
        <th>GENDER</th>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <td>{{user.Name}}</td>
            <td>{{user.Age}}</td>
            <td>{{user.Gender}}</td>
        </tr>
    </tbody>
</table>

reference: https://lodash.com/docs#zip , https://lodash.com/docs#map

Upvotes: 1

Vineet
Vineet

Reputation: 4635

Try something.

<div ng-repeat="user in users.Name">
  Name : {{user}} Age : users.Age[$index]  Gender : users.Gender[$index]
</div>

I assume your object is sequenced and arranged

Upvotes: 1

ryanyuyu
ryanyuyu

Reputation: 6486

Assuming your property arrays all have the same number of elements (and are properly arranged) you could use the $index of ng-repeat.

<table>
    <thead>
        <tr>
            <td>Name</td>
            <td>Age</td>
            <td>Gender</td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="name in obj.Name">
            <td>{{name}}</td>
            <td>{{obj.Age[$index]}}</td>
            <td>{{obj.Gender[$index]}}</td>
        </tr>
    </tbody>
</table>

Alternatively (using the same assumption that the data is well-formed), you can just use javascript to consolidate the three separate lists into a single list of person objects. Then you can proceed like the other examples you've seen.

Javascript might look something like this:

$scope.people = [];
obj.Name.forEach(function(name, index) {
    people.push(
    {
        Name: name,
        Gender: obj.Gender[index],
        Age: obj.Age[index]
    });
});

Then a simple ng-repeat on the new people array will work.

 ...
    <tbody>
        <tr ng-repeat="person in people">
            <td>{{person.Name}}</td>
            <td>{{person.Age}}</td>
            <td>{{person.Gender}}</td>
        </tr>
    </tbody>

Upvotes: 5

Related Questions