Home > Software design >  How to change an array element based on another array element
How to change an array element based on another array element

Time:03-21

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?

CodePudding user response:

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

CodePudding user response:

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