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

99
Visualizações
How to change an array element based on another array element

Whats the goal?
Two arrays: orders and NewOrders

Check if there is an order with the same order_id on both arrays, than compare the order status, if the order from the NewOrders array has a different status then set orders[i].status = NewOrders[i].status

My current code:

const {orders} = this.state;

const page = this.state.page;
const newOrders= await api.get('/orders?page='+page);

for (let i = 0; i < newOrders.length; i++) {
    orders[newOrders[i].order_id].status = newOrders[i].status;             
}

It doesn't properly work
How can I make this work using ES6?

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

0

If you are working in React you must not mutate the state manually. Map orders into a new array, based on the required transformations, then use setState() to update the state.

const _orders = orders.map(o => {
    const found = newOrders.find(no => o.order_id === no.order_id)
    return found
        ? { ...o, status: found.status }
        : o
})

this.setState({orders: _orders})

Example

const orders = [
    { order_id: "1", status: "OK" },
    { order_id: "2", status: "NOK" },
]
const newOrders = [
    { order_id: "2", status: "OK" },
    { order_id: "3", status: "OK" },
]

Output

[
    { order_id: "1", status: "OK" },
    { order_id: "2", status: "OK" },
]
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Array#find.

for (const order of orders) {
    const newOrder = newOrders.find(x => x.order_id === order.order_id);
    if(newOrder) order.status = newOrder.status;
}
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