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

时间:2019-01-25 20:34:24

标签: javascript arrays typescript ecmascript-6

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

因此,我有一个按钮,可以在其中将盘子添加到orders数组。如果它在数组中不存在,则将其推入数组。但是当确实存在时,用新的盘子对象替换当前对象。

它看起来像这样:

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}

比订单数组看起来像这样:

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

有人可以帮助我吗,我很感激:)

2 个答案:

答案 0 :(得分:0)

e.id是订单ID,您可能需要e.dish.id

答案 1 :(得分:-1)

您需要搜索一个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);