【问题标题】:Replace or push to array in javascript在javascript中替换或推送到数组
【发布时间】: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


【解决方案1】:

您可以使用 find()/findIndex() 对数组进行一次循环。

 const index = orderArr.findIndex((obj) => obj.id === webSocketOrder.id);

    if (index === -1) {
        orderArr.push(webSocketOrder);
    } else {
        orderArr[index] = webSocketOrder;
    }

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2011-07-07
    • 2019-05-05
    • 2020-04-18
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多