首页 > 解决方案 > 如何将对象替换为具有特定唯一字段值的数组?

问题描述

我是 TypeScript 和 rxjs 的新手,我有以下问题要解决:我必须根据唯一字段的值将特定对象替换为另一个对象的数组。

我做了类似的事情,从我的数组中删除一个对象,该对象具有这个唯一 ID 字段的特定值:

this.deleteIdAction$.subscribe({
  next: (orderId) => {
    console.log("DELETE ORDER ACTION - ID: ", orderId);
    console.log("ORDERS LIST BEFORE DELETE: ", this.orders);

    this.orders = this.orders.filter(function(obj) {
      return obj.id !== orderId;
    });

    console.log("NEW ORDERS LIST AFTER DELETE: ", this.orders);
  }
});

如您所见,我使用 filter 方法从数组中删除具有特定 ID 字段的对象。如果我必须更新特定对象,我不确定这是正确的选择。

在特定情况下,我必须使用另一种方法将对象更新到以前的this.orders数组中。

this.updateOrderAction.subscribe({
  next: (orderToBeUpdated) => {
    console.log("ORDER OBJECT TO BE UPDATED: ", orderToBeUpdated);

  }
});

在特定情况下,我收到了这个orderToBeUpdated,我必须替换数组的唯一对象,其中id字段等于orderToBeUpdated.id字段值。

什么是实现这种行为的聪明解决方案?

标签: javascripttypescriptrxjs

解决方案


您可以使用数组拼接findIndex函数。

this.updateOrderAction.subscribe({
  next: (orderToBeUpdated) => {
    console.log("ORDER OBJECT TO BE UPDATED: ", orderToBeUpdated);

    const indexToReplace = this.orders.findIndex(order => order.id === orderToBeUpdated.id);
    this.orders.splice(indexToReplace, 1, orderToBeUpdated);
  }
});

推荐阅读