I'm trying to use my json data I got from axios for echarts in my react application but I don't know how to map it correctly.
My current code converts from an array of objects
[
{
"data": "24.64",
"timestamp": "2019-04-30T02:00:42.032Z"
},
{
"data": "24.13",
"timestamp": "2019-04-30T02:20:36.966Z"
}
]
to 2 states
data: ["24.64","24.13"]
timestamp: ["2019-04-30T02:00:42.032Z","2019-04-30T02:20:36.966Z"]
where I call them later with
this.state.data
and
this.state.timestamp
but this doesn't give me the exact chart diagram I want.
This is part of my current working code that fetches and converts the array of objects:
componentDidMount() {
this.getData();
};
getData() {
axios.get('/api/records/datatime')
.then((res) => {
this.setState({
data: res.data.map(({ data }) => data),
timestamp: res.data.map(({ timestamp }) => timestamp),
});
})
.catch((err) => { console.log(err); });
}
What I need now is the array of objects to change to an array of arrays like this in my state, with timestamp as key and data as value.
chartData:
[
["2019-04-30T02:00:42.032Z","24.64"],
["2019-04-30T02:20:36.966Z","24.13"]
]
You can use Object.values()
this.setState({
chartData:res.data.map(Object.values)
});
A working snippet in plain js
const arr= [ { "data": "24.64", "timestamp": "2019-04-30T02:00:42.032Z" }, { "data": "24.13", "timestamp": "2019-04-30T02:20:36.966Z" } ] const res = arr.map(Object.values) console.log(res)
Use map
and Object.values
, then reduce
to make the object:
const data = [{"data":"24.64","timestamp":"2019-04-30T02:00:42.032Z"},{"data":"24.13","timestamp":"2019-04-30T02:20:36.966Z"}]; const res = data.map(Object.values).reduce((acc, [d, t]) => { acc.data.push(d); acc.timestamp.push(t); return acc; }, { data: [], timestamp: [] }); console.log(res)
.as-console-wrapper { max-height: 100% !important; top: auto; }
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.