I have a REST service that returns me a JSON data similar to the below format:
{
"Africa" : [{
"country" : "Nigeria",
"capital" : "Abuja"
}, {
"country" : "Kenya",
"capital" : "Nairobi"
}, {
"country" : "Ghana",
"capital" : "Accra"
}
],
"Asia" : [{
"country" : "India",
"capital" : "New Delhi"
}, {
"country" : "China",
"capital" : "Beijing"
}
],
"Europe" : [{
"country" : "France",
"capital" : "Paris"
}
]
}
How should I parse this result and populate a table which would look similar to the image below:
asked Nov 2, 2016 at 17:57
FakirTrappedInCode
6599 silver badges31 bronze badges
2 Answers 2
Try this one Fiddle
<table ng-app="testApp" ng-controller="testController">
<tr>
<td>Contitent</td>
<td>Country</td>
<td>Capital</td>
</tr>
<tr ng-repeat-start="(key, val) in testData">
<td rowspan="{{val.length}}">{{key}}</td>
<td>{{val[0].country}}</td>
<td>{{val[0].capital}}</td>
</tr>
<tr ng-repeat-end ng-repeat="value in val.slice(1)">
<td>{{value.country}}</td>
<td>{{value.capital}}</td>
</tr>
Sign up to request clarification or add additional context in comments.
2 Comments
FakirTrappedInCode
Thanks. ng-repeat-start/ng-repeat-end solution seems neat. But Iam not sure about performance of this solution compared to @wander-nauta
Markus
I don't see any big performance impact between those two approaches, you man test on bigger data like 100K rows...
You could try something like this:
<table>
<thead>
<tr>
<th>Continent</th>
<th>Country</th>
<th>Capital</th>
</tr>
</thead>
<tbody ng-repeat="(continent, countries) in yourjsondata">
<tr ng-repeat="country in countries">
<td ng-if="$first" rowspan={{countries.length}}>{{ continent }}</td>
<td>{{ country.country }}</td>
<td>{{ country.capital }}</td>
</tr>
</tbody>
</table>
This creates a tbody for every continent, and a tr for every country. Only the first row of a continent gets a cell for the name of that continent. That cell also gets a rowspan attribute so that it spans multiple rows.
answered Nov 2, 2016 at 18:19
Wander Nauta
19.7k1 gold badge50 silver badges65 bronze badges
Comments
lang-js