我正在循環將數組的數組轉換爲對象,我使用逗號「」分割,但如果我的值有一些逗號,它也會被分割。例如:如果我的價值有一個日期2017年5月2日它實際上是一個單一的價值,但它是分裂爲5月2日作爲一個值和2017作爲另一個值,所以,我的整個目標變得越來越.need幫助Array of Array to Json
我我正在閱讀excel表格。我的輸出是數組的數組。我需要將其轉換爲json對象。
var xls = require('excel');
describe('TransactionDetails-Excel', function() {
it('External Type G Tranasaction Details validation', function (done) {
xls('transactions.xlsx', function(err, data) {
if(err){
throw err;
}
else{
console.log(data);
console.log(JSON.stringify(convertToJSON(data)));
done();
}
});
function convertToJSON(array) {
var first = array[0].join();
var headers = first.split(',');
var jsonData = [];
for (var iterator_i = 1, length = array.length; iterator_i < length; iterator_i++){
var myRow = array[iterator_i].join();
var row = myRow.split(',');
var data = {};
for (var x = 0; x < row.length; x++){
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
}
});
});
Excel表:transactions.xlsx click here to view screenshot of excel sheet
輸出:數據
[ [ 'Transaction Id', 'Paid ', 'Time Created' ],
[ '0YC0',
'Joe\'s Generic Business \[email protected]',
'Mar 2, 2012 14:28:36 PST' ],
[ '8uyhr', '[email protected]', 'May 2, 2015 15:20:20 PST' ],
[ '786YUH', '[email protected]', 'May 18, 2017 13:20:30 PST' ] ]
輸出://這是我所得到的
[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \[email protected]","Time Created":"Mar 2","undefined":" 2012 14:28:36 PST"},
{"Transaction Id":"8uyhr","Paid ":"[email protected]","Time Created":"May 2","undefined":" 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"[email protected]","Time Created":"May 18","undefined":" 2017 13:20:30 PST"}]
但最終目標應該是:
[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \[email protected]","Time Created":"Mar 2, 2012 14:28:36 PST"},
{"Transaction Id":"8uyhr","Paid ":"[email protected]","Time Created":"May 2, 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"[email protected]","Time Created":"May 18, 2017 13:20:30 PST"}]
在此先感謝。
看到這個https://stackoverflow.com/questions/22917269/javascript-convert-two-dimensional-array -to-array-of-objects-using-the-first-r – barbsan
爲什麼使用'join()'然後是'split()'。在join之前直接使用數組,它會正常工作。 –