我有一个多维对象数组,它对 Angular 的 ng-repeat 造成严重破坏,因此我想将其转换为一维数组。我尝试使用 forEach
这样做,但失败了。当我在运行该函数后尝试使用 console.log(newData) 时,它返回一个空数组。是我把事情想得太简单了,还是我犯了一个愚蠢的错误?
//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);
最佳答案
这可能会帮助您避免过于字面化...请注意,容器数组被跳过(例如“部分”和“详细信息”)
// Helper functions
function isArray(obj) {return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) === '[object Array]';}
function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]' && isFinite(val);}
// Flatten object
function flatten(arg, out) {
out = out || {};
for (var prop in arg) {
var val = arg[prop];
if (isArray(val)) {
for (var i = 0; i < val.length; i++) {
// introspect if the array is just an array of numbers
var valin = val[i];
if (isArray(val) && isNumber(valin)) {
// just set to the number array and move along.
out[prop] = val;
break;
} else {
flatten(valin, out);
}
}
// continue looking deeper
} else if (typeof val == "object") {
flatten(val, out);
// get the value
} else {
out[prop] = val;
}
}
return out;
}
// Put each flattened object into a new data array
var data = [];
for (var i = 0; i < allData.length; i++) {
data.push(flatten(allData[i]));
}
console.log(JSON.stringify(data));
关于javascript - 将多维对象数组转换为单维对象数组 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768537/