How to create the data as an array of objects with a limit of 5 data in JavaScript.
I am using web socket and getting this call first time
[
{city:"Newyork",value:10,"time":"13:8"},
{city:"London",value:20,"time":"13:8"}
]
Now In the second call, I will get data like that
[
{city:"Newyork",value:150,"time":"13:20"},
{city:"London",value:25,"time":"13:20"}
{city:"Sydney",value:20,"time":"13:20"}
]
So what I am doing here is I am adding new data and updating the existing data and then updating my state. Here is the code for that.
var city = this.state.city;
for(var j=0; j<res.length; j++){
const i = city.findIndex(_item => _item.city === res[j].city);
if (i > -1) city[i] = res[j]; // (2)
else city.push(res[j]);
}
this.setState({data:city})
This is working fine.
Now How I declare a state where I have to update five data which based on the last five WebSocket call.
Somewhat like this
myData = [{newyork:{[value:10,time:13:20],[value:150,time:13:20]}},London:{[value:20,time:13:20],[value:25,time:13:20]},Sydney:{[value:20,time:13:20]}];
So Based on this data I can plot a chart of a specific city. I need only 5 data of each city.
Can anyone help me here?
On each update, for each city, you can do something like this:
if(city[city_name].length >= 5){
city[city_name].shift();
}
city[city_name].push(new_city);