1 回答
TA贡献1872条经验 获得超3个赞
我已经完成了一个要求,如下所示。请尝试此示例并实现其他示例。
import React, {Component} from "react";
export default class JsonExample extends Component {
state = {
updatedJson: []
};
json = [
{date: "2018-01-01", import: "XXX <--number"},
{date: "2018-03-03", import: "XXX<--number"},
{date: "2018-03-20", import: "XXX<--number"},
{date: "2018-03-25", import: "XXX<--number"},
{date: "2020-05-01", import: "XXX<--number"},
{date: "2020-05-02", import: "XXX<--number"},
{date: "2020-05-03", import: "XXX<--number"},
];
componentDidMount() {
let updatedJson = [];
this.json.map(value => {
let d = new Date(value.date);
let yearMonth = ("0" + (d.getMonth() + 1)).slice(-2) + "-" + d.getFullYear();
updatedJson.push(yearMonth);
});
this.setState({updatedJson: updatedJson});
}
render() {
return (
<div>
{JSON.stringify(this.state.updatedJson)}
</div>
);
}
}
根据要求更新了完整代码
import React, {Component} from "react";
export default class JsonExample extends Component {
state = {
monthlyData: [],
sortedData: [],
monthlyTotalImport: []
};
json = [
{date: "2018-01-01", import: 7},
{date: "2018-01-21", import: 1},
{date: "2018-03-03", import: 10},
{date: "2018-03-20", import: 10},
{date: "2020-05-01", import: 10},
{date: "2017-12-01", import: 5},
{date: "2020-05-02", import: 10},
{date: "2020-05-03", import: 10},
];
componentDidMount() {
let data = [];
this.json.map(value => {
let d = new Date(value.date);
data.push({...value, date2: d});
});
let sortedData = data.sort((a, b) => a.date2 - b.date2);
console.log(sortedData, 'sorted');
let monthlyData = [];
sortedData.map(value => {
let d = new Date(value.date);
let yearMonth = ("0" + (d.getMonth() + 1)).slice(-2) + "-" + d.getFullYear();
monthlyData.push({...value, yearMonth: yearMonth});
});
console.log(monthlyData, 'monthly data');
let result = monthlyData.reduce((acc, item) => ({
...acc,
[item.yearMonth]: (acc[item.yearMonth] || 0) + item.import
}), {});
this.setState({monthlyTotalImport: result});
console.log(result, 'result');
}
render() {
return (
<div>
{JSON.stringify(this.state.monthlyTotalImport)}
</div>
);
}
}
添加回答
举报