代码之家  ›  专栏  ›  技术社区  ›  Sireini

如何检查数组中的对象id是否相同?

  •  -1
  • Sireini  · 技术社区  · 7 年前

    我想将一个对象id与数组中对象的所有id进行比较。

    因此,我有一个按钮,可以将一道菜添加到订单数组中。当它不在数组中时,将其推送到数组中。但是当它确实存在时,用新的dish对象替换当前的。

    const dish = {id:1, quantity: 4};
    
    // This will be filled by an array push
    const orders = [
      {id: 1, dish: {id:1, quantity: 1}},
      {id: 2, dish: {id:3, quantity: 5}},
      {id: 3, dish: {id:5, quantity: 1}},
      {id: 4, dish: {id:2, quantity: 3}},
      {id: 5, dish: {id:8, quantity: 1}}
    ]
    

    所以基本上我有一个 orderID dishID

    我所尝试的:

    addToCart(dish){
    
      const index = this.orders.findIndex((e) => e.id === dish.id);
    
       if(index >= 0){
          console.log('INDEX1', this.orders, index);
          this.orders[index] = {id: this.orders[index].id, dish: this.orders[index].dish};
       } else {
          this.orderCounter = this.orderCounter + 1;
          this.orders.push({id: this.orderCounter, dish: dish});
       }
    }
    

    index 当我两次添加第三道菜时返回-1,如下所示:

    dish = {id: 3, quantity: 2}
    

    而orders数组如下所示:

    const orders = [
      {id: 0, dish: {id:1, quantity: 1}},
      {id: 1, dish: {id:3, quantity: 2}},
      {id: 2, dish: {id:3, quantity: 2}},
    ]
    

    谁能帮帮我吗我很感激:)

    2 回复  |  直到 7 年前
        1
  •  0
  •   Jonas Wilms    7 年前

    e.id 是您可能想要的订单id e.dish.id .

        2
  •  -1
  •   Shidersz    7 年前

    dish.id 属性已存在,您的实际代码与 order id . 此外,我还做了一些其他小改动来修复您的代码,请检查以下内容:

    const orders = [
        {id: 0, dish: {id:1, quantity: 1}},
        {id: 1, dish: {id:3, quantity: 2}}
    ];
    
    let orderCounter = 1;
    
    function addToCart(dish)
    {
       const index = orders.findIndex(({dish:{id}}) => id === dish.id);
    
       if (index >= 0)
       {
          orders[index].dish = dish;
       }
       else
       {
          orders.push({id: ++orderCounter, dish: dish});
       }
    }
    
    addToCart({id: 3, quantity: 5});
    addToCart({id: 7, quantity: 3});
    console.log(orders);
    推荐文章