如何根据另一个数组元素更改数组元素
How to change an array element based on another array element
目标是什么?
两个数组:orders 和 NewOrders
检查两个数组中是否存在具有相同 order_id
的订单,然后比较订单状态,如果 NewOrders 数组中的订单具有不同的状态则设置 orders[i].status = NewOrders[i].status
我当前的代码:
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;
}
无法正常工作
我怎样才能使用 ES6 完成这项工作?
您可以使用 Array#find
.
for (const order of orders) {
const newOrder = newOrders.find(x => x.order_id === order.order_id);
if(newOrder) order.status = newOrder.status;
}
如果您在 React 中工作,则不得手动更改状态。根据所需的转换将订单映射到新数组,然后使用 setState()
更新状态。
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})
例子
const orders = [
{ order_id: "1", status: "OK" },
{ order_id: "2", status: "NOK" },
]
const newOrders = [
{ order_id: "2", status: "OK" },
{ order_id: "3", status: "OK" },
]
输出
[
{ order_id: "1", status: "OK" },
{ order_id: "2", status: "OK" },
]
目标是什么?
两个数组:orders 和 NewOrders
检查两个数组中是否存在具有相同 order_id
的订单,然后比较订单状态,如果 NewOrders 数组中的订单具有不同的状态则设置 orders[i].status = NewOrders[i].status
我当前的代码:
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;
}
无法正常工作
我怎样才能使用 ES6 完成这项工作?
您可以使用 Array#find
.
for (const order of orders) {
const newOrder = newOrders.find(x => x.order_id === order.order_id);
if(newOrder) order.status = newOrder.status;
}
如果您在 React 中工作,则不得手动更改状态。根据所需的转换将订单映射到新数组,然后使用 setState()
更新状态。
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})
例子
const orders = [
{ order_id: "1", status: "OK" },
{ order_id: "2", status: "NOK" },
]
const newOrders = [
{ order_id: "2", status: "OK" },
{ order_id: "3", status: "OK" },
]
输出
[
{ order_id: "1", status: "OK" },
{ order_id: "2", status: "OK" },
]