我需要了解如何在 Angular/JS 中创建多维对象或数组。这个JSFiddle应该清楚地解释了问题:https://jsfiddle.net/s3etbdyj/5/
如何在 forEach 循环中进行 forEach 循环?总结一下:
我有一些数据很容易在我的应用程序中显示。
"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",
}],
}]
正如您所看到的,每个“专辑”对象可以在其中包含多个“歌曲”对象。
我需要循环遍历这些数据并重建它(以便我可以添加内容并按照我认为合适的方式格式化它)
如何在此结构中创建嵌套对象数据?这是我到目前为止所拥有的:
$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)
但这行不通。它创建了一个扁平结构:
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...
看看 JSfiddle:https://jsfiddle.net/s3etbdyj/5/ 谁能让我的 newData 看起来就像我的 origData 一样,从而解释如何创建嵌套对象?! 谢谢。
最佳答案
试试这个:
$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);
关于javascript - 在 Angular 中创建多维/嵌套对象(嵌套 forEach 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39769548/