I have a JSON array like this:
Array = [{"type":"x", "name":"a1"},
{"type":"x", "name":"a2"},
{"type":"y", "name":"a3"},
{"type":"y", "name":"a4"}]
Now, I'd like to show it in a table, using Angular, so that it takes this form:
x
a1
a2
y
a3
a4
The table shows the type and then the name of all the items which have that type.
First of all, wild man @Morre is correct (albeit a little excited about his correctness) that what you have is not a JSON array but rather an array of objects. But semantics aside...
While I'm confident there is a more elegant way of approaching your problem, here is one possible solution
// Given your array
var myArray = [{
"type": "x",
"name": "a1"
}, {
"type": "x",
"name": "a2"
}, {
"type": "y",
"name": "a3"
}, {
"type": "y",
"name": "a4"
}];
// create a new object structured like this
// {'x': ['a1', 'a2'], 'y': ['a2', 'a3']}
// while creating a new array that's structured like this
// ['x', 'a1', 'a2', 'y', 'a2', 'a3']
var newObj = {};
$scope.newArray = [];
myArray.map(function(obj) {
if (!newObj[obj.type]) {
newObj[obj.type] = [obj.name];
$scope.newArray.push(obj.type);
$scope.newArray.push(obj.name);
} else {
newObj[obj.type].push(obj.name);
$scope.newArray.push(obj.name);
}
});
and your ng-repeat
could look like this
<tr ng-repeat="value in newArray">
<td>{{ value }}</td>
</tr>
See JSFiddle for more details
You can use ngrepeat, however you would need to change your object structure such that "type" becomes a parent of "name": var obj = {type: 'x', names: [{name:'a1'}, {name:'a2'}]}
OR
If you are dealing with a large dataset and cannot change the structure of your object for performance, you may want to consider writing an angular custom directive.