1

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"]
  ]

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.