I have an array with 3 Objects, however the second Object does not have an array inside the ' Data ' Object.
I need to do an ng-repeat for each 'Artist' in the correct order, however the second object is causing issues. How would I combine each Object together?
In my Factory, I set up a call to receive three response from three different API. I set a promise for each one so they come in a the exact order I call them.
FACTORY
.factory('timeline', function($http, $q) {
var promise1 = $http({
method: "GET",
url: "http://api.example.com/last/3/?limit=3"
});
var promise2 = $http({
method: "GET",
url: "http://api.example.com/current/3/"
});
var promise3 = $http({
method: "GET",
url: "http://api.example.com/next/3/?limit=3"
});
return {
data: $q.all([promise1, promise2, promise3])
}
})
In my controller, I get the response like so.
[
Object
config
data: [Array 3]
-0: Object
artist : 'Artist'
title : 'Title'
-1: Object
-2: Object
,
Object
config
data: Object
artist : 'Artist'
title : 'Title
,
Object
config
data: [Array 3]
-0: Object
artist : 'Artist'
title : 'Title'
-1: Object
-2: Object
]
CONTROLLER
My Attempt to filter using Underscore.
.controller('StationCtrl', function($scope, $stateParams, $http, timeline) {
timeline.data.then(function(musicData) {
var row = [];
for (var i = 0; i < musicData.length; i++) {
var data = _.filter(musicData[i].data, function(x){
row.push(x);
})
}
})
})
My Goal eventually if possible would be to combine everything in order
Object
data: [Array 7]
-0: Object
-1: Object
-2: Object
-3: Object
-4: Object
-5: Object
-6: Object
,
I am still trying to figure out how to work with Objects & Arrays, any help/tips would be great.
理想情况下,我认为您应该只为长度为1的第二个对象发送一个数组。如果API不在您的控制范围内(例如,第三方或其他任何对象),那么我们期待以其他方式解决该问题。
This is a simple approach of how you can solve your problem without underscore. You just need to check whether your data is an object or an array.
var arr = [
{ data: [{ artist: 'Artist' }, { artist: 'Artist2' }]},
{ data: { artist: 'Artist3' } },
{ data: [{ artist: 'Artist4' }]}
];
var flattened = [];
arr.forEach(function (el) {
if(Array.isArray(el.data)) {
flattened = flattened.concat(el.data);
} else {
flattened.push(el.data);
}
});
See example on jsbin .
You could strip out the underscore and just do a nested for:
.controller('StationCtrl', function($scope, $stateParams, $http, timeline) {
timeline.data.then(function(musicData) {
var row = [];
var dataElement;
var i;
var j;
for (i = 0; i < musicData.length; i++) {
dataElement = musicData[i].data;
if(typeof dataElement === 'object') {
row.push(dataElement)
} else if(typeof dataElement === 'array') {
for(j = 0; j < dataElement.length; j++) {
row.push(dataElement[j]);
}
}
}
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.