【发布时间】:2021-08-14 16:26:43
【问题描述】:
我有一个订单数组,当我从我的 websocket 收到一条带有新放置订单或修改订单的消息时,我想检查我的订单数组,如果存在带有 websocket 消息的订单,请替换其中的对象带有 websocket 消息的数组,否则将其推送到数组。
示例:
const orderArr = [
{
id: 1,
item: 'apple',
price: 20
},
{
id: 2,
item: 'mango',
price: 10
},
{
id: 3,
item: 'cucumber',
price: 300
}
]
const webSocketOrder = {
id: 1,
item: 'apple',
price: 40
}
// what should happen to the order array
[
{
id: 1,
item: 'apple',
price: 40
},
{
id: 2,
item: 'mango',
price: 10
},
{
id: 3,
item: 'cucumber',
price: 300
}
]
但如果webSocketOrder 是具有新ID 的新项目,则应将其作为新项目添加到orderArr 中
我做了什么
const foundOrder = orderArr.find(
(x) => x.id === webSocketOrder.id
);
if (foundOrder) {
orderArr.map((ord) =>
ord.id === webSocketOrder.id
? webSocketOrder
: ord
);
} else {
orderArr.unshift(webSocketOrder);
}
由于某种原因这不起作用,请有人帮忙吗?
【问题讨论】:
-
代码中的任何地方都没有打字稿...
-
我的错误,我删除了那些位
-
详细了解数组操作。您的 find、map 和 unshift 用法是错误的
-
为什么要像函数一样调用数组:
orderArr( (x) => ..) -
对不起,这是 orderArr.find
标签: javascript node.js algorithm