0
我正在生成一系列嵌套對象(在元素的'failReasons'和'照片'下)的對象數組 - 然後我想將結果數組作爲JSON到一個Web API,它將期望一個對象列表,以及嵌套的對象列表。第一部分工作 - 數組接收對象列表並可以解析它們,但是,在將數組轉換爲JSON時,嵌套數組爲空。使用嵌套對象數組的JSON.Stringify數組TypeScript/JS
這是我產生了數組: 這裏是個什麼樣子,當我字符串化是這樣的:
{"capeNo":"ABCD1234","insDate":"2016-11-10 15:03:18","inspector":"User.Name","inspectionResult":"Pass","comments":"","site":"Site Name","dismCompleteDate":"","failReasons":[],"photos":[]}
正如你所看到的,failReasons,它有它的數組中的6個對象被字符串化之前,現在只是一個空陣列。
我用下面的代碼來生成數組:
接口:
export interface inspectionUpload {
capeNo: string;
insDate: string;
inspector: string;
inspectionResult: string;
comments: string;
site: string;
dismCompleteDate;
failReasons: Array<Object>;
photos: Array<Object>;
}
export interface inspectionFailures {
failCategory: string;
failReason: string;
resolution: string;
inspectionId: string;
}
export interface inspectionPhotos {
base64: string;
}
而這種填充陣列:
this.sql.query('SELECT rowid,* FROM InspectionResults_tbl').then((res) => {
var arr = []
for (var i = 0; i < res.res.rows.length; i++) {
var item = res.res.rows.item(i);
var header: inspectionUpload = {
capeNo: item.capeNo,
insDate: item.inspectionDT,
inspector: item.inspectedBy,
inspectionResult: item.result,
comments: item.comment,
site: this.SharedService.site,
dismCompleteDate: item.dismantleDate,
failReasons: <inspectionFailures[]> [],
photos: <inspectionPhotos[]> []
}
if (item.result == 'Fail') {
console.log(item);
this.sql.query('SELECT * FROM InspectionFailures_tbl WHERE inspectionId = ?', [item.rowid]).then((res) => {
for (var i = 0; i < res.res.rows.length; i++) {
var item = res.res.rows.item(i);
header.failReasons.push({
failCategory: item.failCategory,
failReason: item.failreason,
resolution: item.resolution,
FRId: item.FRId
})
}
})
}
this.sql.query('SELECT * FROM InspectionPhotos_tbl WHERE inspectionId = ?', [item.rowid]).then((res) => {
for (var i = 0; i < res.res.rows.length; i++) {
var item = res.res.rows.item(i);
header.photos.push({
base64: item.base64
})
}
})
arr.push(header);
if ((i + 1) == res.res.rows.length) upload(arr)
}
})
最後,以字符串化它:
function upload(a) {
console.log(a);
console.log(JSON.stringify(a));
}
幫助將不勝感激:)
在外部查詢的回調中執行的那些查詢與該查詢的異步性相同。這些查詢完成後,數組將填充,但在外部回調完成後會發生這種情況。 – Pointy
@Pointy,如果我遵循,你是說在我的失敗原因和照片數組填充之前調用json.stringify?我曾經考慮過這個問題,但是在我將它串起來的同時,我調用了數組的console.log,並且當時可以看到數據(根據屏幕截圖?)或者我誤解了它們嗎? – fl3rgle
頂級對象'已經登錄了,在你的圖像的最上面的框架中,它旁邊是否有一個小的藍色'i'? –