对象数组中的角度更新对象

新手上路,请多包涵

假设我有以下对象数组,我们将其命名为 itemArray;

 {
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}

而且我有一个订阅,它只返回 id 2 的更新结果。如何在不循环整个数组的情况下更新对象数组?

我想要的是下面的例子;

 updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }

甚至更好的是,替换整个对象;

   updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }

但是,此示例根据数组的索引更新数组。那么我该如何根据 newitem.id 进行更新呢?

评论中要求的模板:

 <tr *ngFor="let u of itemsArray.items; let i = index">
  <td>{{ u.id }}</td>
  <td>{{ u.name }}</td>
  <td>
    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
    <label for="singleCheckbox-{{i}}"></label>
  </td>
</tr>

原文由 phicon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 687
2 个回答

我根据您的示例创建了这个 Plunker ,该示例更新了等于 newItem.id 的对象

这是我的功能片段:

 showUpdatedItem(newItem){
    let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);

    let index = this.itemArray.items.indexOf(updateItem);

    this.itemArray.items[index] = newItem;

  }

  findIndexToUpdate(newItem) {
        return newItem.id === this;
  }

希望这可以帮助。

原文由 Nehal 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以更新一项,例如。

 let item = list.find(item => item.id === id);

if(item)
{
  item.name = 'other name';
}

原文由 Oscar de la torre 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进