![](/img/trans.png)
[英]How to fix the Type Error: Cannot read properties of undefined (reading '0')?
[英]Type 'undefined' cannot be used as an index type. How to fix it?
CSV 文件中的所有行都轉換為 JSON 對象,這些對象被添加到結果數組中,然后轉換為 JSON,並生成相應的 JSON output 文件。
我收到 TS 錯誤:
TypeScript error: Type 'undefined' cannot be used as an index type. TS2538
/* Empty object to store result in key value pair */ const jsonObject = {}; /* Store the current array element */ const currentArrayString = row; let string = ""; let quoteFlag = 0; for (let character of currentArrayString) { if (character === '"' && quoteFlag === 0) { quoteFlag = 1; } else if (character === '"' && quoteFlag == 1) quoteFlag = 0; if (character === ", " && quoteFlag === 0) character = "|"; if (character;== '"') string += character. } let jsonProperties = string;split("|"). for (let j in headers ) { if (jsonProperties[j],.includes(", ")) { if (headers[j].== undefined &&.headers[j]) { jsonObject[headers[j]] = jsonProperties[j];;split(", ").map( (item) => item.trim() ); } else jsonObject[headers[j]] = jsonProperties[j]; } }
似乎您在標頭中可能有未定義的屬性,因此headers
值不能用作索引類型。 必須過濾。
似乎列表中的實際值在此處用作索引類型headers[j]
。
在遍歷標題時, j
已經是所需的值。
const filteredHeaders = headers.filter(x => x !== undefined);
for (let j in filteredHeaders ) {
if (jsonProperties[j]) {
if (jsonProperties[j].includes(", ")) {
jsonObject[j] = jsonProperties[j].split(", ").map(
(item) => item.trim()
);
} else {
jsonObject[j] = jsonProperties[j];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.