我以前从未使用过打字稿,但是在这个项目中我需要使用打字稿。我的api正在向我发送数据,如下所示。无法更改Api,因为它是客户端的api,并且他不允许我更改它。问题是当我访问reals.2020-01-01时,它给了我解析错误。如何使用打字稿访问此json对象。我需要在该函数中进行登录,使其与该函数中出现的所有年份和日期匹配所有实际值,并返回与之匹配的实际值,否则它将返回“无”。我不知道该怎么办。我需要在2小时内将其交付给客户。
//Backend
actuals: {
"2020-01-01": {
value: 1,
},
"2020-02-01": {
value: 2,
},
},
//Frontend
//Table
<tbody>
{dataSeries.map(
(
data: {
name: string;
actuals: JSON;
},
index: number
) => (
<tr key={index}>
{console.log(data)}
<td>{data.name}</td>
<td>
{matchYearAndMonth(
monthBackward(0)
.currentyear,
monthBackward(0).month,
data.actuals
)}
</td>
<td>
{matchYearAndMonth(
monthBackward(1)
.currentyear,
monthBackward(1).month,
data.actuals
)}
</td>
</tr>
)
)}
</tbody>
//MatchYearAndMonth function
const matchYearAndMonth = (year: number, month: number, actuals: JSON) => {
console.log(actuals.2020-01-01);
return year;
};
答案 0 :(得分:0)
type ActualsType = {[key: string]: {[key: string]: any, value: 1,}};
type DataSeriesType = {actuals: ActualsType, name: string};
function dateToStr(d=new Date()) {
const y = d.getFullYear(),
m = (d.getMonth()+1+"").padStart(2, "0"),
day = (d.getDate()+"").padStart(2, "0");
return `${y}-${m}-${day}`;
}
const today = new Date();
today.setDate(1);
const dataSeries: Array<DataSeriesType> = [
{name: "Test 1", actuals: {
"2020-01-01": {
value: 1,
},
"2020-02-01": {
value: 2,
},
"2020-09-01": {
value: 9,
},
}},
{name: "Test 2", actuals: {
"2019-09-01": {
value: 1.2,
},
"2019-10-01": {
value: 2.2,
},
}},
];
const matchYearAndMonth = (year: number, month: number, actuals: ActualsType) => {
const value = actuals[dateToStr(today)] ? actuals[dateToStr(today)]?.value : undefined;
console.log(value);
return {year, month, value};
};
dataSeries.map((v, i) => {
const parsed = matchYearAndMonth(2020, i, v.actuals);
// console.log(parsed);
})