This reads the string and creates and array of objects which is used in various operations but when the final array is returned I need the year to be a number but at the moment it is a string
for (let i = 1; i < allFileLines.length; i++) {
const data = allFileLines[i].split("|");
if (data.length === newheaders.length) {
const tarry: Icface = {
title: null as string,
id: null as string,
year: null as number,
};
for (let j = 0; j < newheaders.length; j++) {
tarry[newheaders[j]] = data[j];
}
if (typeof tarry[2] === "number") {
Log.trace("number");
}
// tslint:disable-next-line:no-console
// console.log(lines);
// Log.trace(JSON.parse(JSON.stringify(tarry)));
lines.push(tarry);
}
}
and interface is
export interface Icface {
title: string;
id: string;
year: number;
[key: string]: string | number;
}
So after the processing the year is being returned as "2018" but it needs to be 2018. Kind of baffling that I am able to operate on the string year with < and ===. Any ideas?
You have split a string into an array of strings, try
const tarry: Icface = {
title: data[0],
id: data[1],
year: parseInt(data[2]),
};
The interface Icface below allows the property year
be string or number
export interface Icface {
title: string;
id: string;
year: number;
[key: string]: string | number; // it allows ['year'] be string or number
}
Please try changing the for loop of for (let j = 0; j < newheaders.length; j++)
as
for (let j = 0; j < newheaders.length; j++) {
if (newheaders[j] === 'year') {
tarry.year = +data[j];
else {
tarry[newheaders[j]] = data[j];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.