javascript - 如何将对象替换为具有特定唯一字段值的数组?
问题描述
我是 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字段值。
什么是实现这种行为的聪明解决方案?
解决方案
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);
}
});
推荐阅读
- functional-programming - 我将如何在球拍中创建一个否定二进制函数
- flutter - 如何在颤动中使用文本字段制作数字计数器应用程序?
- excel - 查找列范围内的短语?
- spring-boot - NUnit 5 Spring MVC 测试 NoSuchBeanDefinitionException 用于子模块中的 Autowired 依赖项
- excel - 如何找到列标题并返回列号vba
- momentjs - Moment JS插件的错误日期
- javascript - 我选择一种红色,然后如果我单击第二张图像的左上角,它会变成红色
- c# - 移除 shell 操作栏 Xamarin Forms Android 下的阴影
- android - 如何通过返回按钮传递数据,Kotlin
- c - c 中 char 数组的第一个值以 int 形式返回?