Leon Leon - 2 months ago 17
Javascript Question

Create multidimensional / nested object in Angular (nested forEach loops)

I need to understand how to create a multidimensional object or array in Angular / JS. This JSFiddle should explain the problem clearly: https://jsfiddle.net/s3etbdyj/5/

How do I forEach loop within a forEach loop? To summarise:

I have some data which is easy to display in my application.

"albums":[{
"album_id": 1,
"album_title": "Test Release",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"songs": [{
"id": 114,
"title": "Test song",
}, {
"id": 115,
"title": "Test song 2",
}],
}, {
"album_id": 2,
"album_title": "Blood Sugar Sex Magik",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"songs": [{
"id": 116,
"title": "Give It Away",
}, {
"id": 117,
"title": "Under The Bridge",
}],
}]


As you can see, each "albums" object can have several "songs" objects within it.

I need to loop through this data and rebuild it (so that I can add things and format it as I see fit)

How do I create nested objects data in this structure? Here's what I have so far:

$scope.newData = [];

// create formatted song list
angular.forEach($scope.origData, function(m) {
$scope.newData.push({
'album_id' : m.album_id,
'album_title' : m.album_title,
});
angular.forEach(m.songs, function(tr) {
var obj = {
id: tr['id'],
title: tr['title'],
}
$scope.newData.push(obj);
});
}, $scope.newData)


But that doesn't work. It creates a flat structure:

Object:
{
"album_id": 1,
"album_title": "Test Release",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
}
Object:
{
"id": 114,
"title": "Test song",
}
Object:
{
"id": 115,
"title": "Test song 2",
}
etc...


Have a look at the JSfiddle: https://jsfiddle.net/s3etbdyj/5/
Can anyone make my newData look just like my origData, thus explaining how nested objects are created?!
Thanks.

Answer

Try this:

  $scope.newData = [];

  // create formatted song list
    angular.forEach($scope.origData, function(m) {
            var album = {
              'album_id': m.album_id,
              'album_title': m.album_title,
              'songs': []
            };
            $scope.newData.push(album);
            angular.forEach(m.songs, function(tr) {
                var obj = {
                    id: tr['id'],
                    title: tr['title'],
                };
                album.songs.push(obj);
            });
    }, $scope.newData);
Comments