Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
How to create the data as an array of object with limit of 5 data in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda