I have a multi-dimensional array of objects that is wreaking havoc on Angular's ng-repeat, so I want to convert it to a single-dimensional array. I tried and failed to do so using forEach. When I try to use console.log(newData) after running the function, it returns an empty array. Am I making it too simple, or did I make a stupid mistake?
//Sample data (allData):
var allData = [{
"period": 4,
"uploadDate": "2015-11-19T21:00:00.000Z",
"section": [{
"transferCode": 8675309,
"details": [{
"voucherNumber": [34, 22],
"vendor": "jimmy",
"description": "blah ",
"amount": "t 45,555.00"
}]
}]
}, {
"period": 4,
"uploadDate": "2015-11-19T21:00:00.000Z",
"section": [{
"transferCode": 45576543,
"details": [{
"voucherNumber": [22, 33],
"vendor": "Jonson",
"description": "trap music ",
"amount": "t 12,345.00"
}]
}]
}]
//code to push to new array:
var newData = [];
function newArray() {
allData.forEach(function(top) {
top.section.forEach(function(mid) {
mid.details.forEach(function(low) {
newData.push({
vendor: low.vendor,
voucherNumber: low.voucherNumber,
description: low.description,
amount: low.amount,
transferCode: mid.transferCode,
uploadDate: top.uploadDate,
period: top.period
})
})
})
})
return newData;
}
newArray();
document.body.textContent = JSON.stringify(newData);
newDatashould be declared (or at least re-initialized) inside the function. As it is, if you call the function twice, it'll add everything to the end of the existing array.