JavaScript中替换对象数组中匹配ID的对象问题
替换数组中ID匹配的完整对象解决方案
你之前用find的方式无效,是因为回调函数里的data只是当前元素的局部引用,直接给data赋值myObject只会修改这个局部变量,根本影响不到原数组里的元素。
下面给你几种可行的解决方法:
方法一:通过索引直接替换(修改原数组)
用findIndex找到匹配元素的位置,然后替换原数组对应索引的元素:
const targetIndex = this.integrationActionsArray.findIndex(item => item.id === myObject.id); if (targetIndex !== -1) { this.integrationActionsArray[targetIndex] = myObject; }
方法二:用map生成新数组(不修改原数组,返回新数组)
如果不想改动原数组,可以用map遍历生成新数组,匹配ID的元素替换成新对象,其余保留原元素:
this.integrationActionsArray = this.integrationActionsArray.map(item => item.id === myObject.id ? myObject : item );
方法三:用forEach遍历替换(修改原数组)
利用forEach的索引参数,找到匹配元素后直接修改原数组:
this.integrationActionsArray.forEach((item, index) => { if (item.id === myObject.id) { this.integrationActionsArray[index] = myObject; } });
测试任意一种方法后,你再打印this.integrationActionsArray就能得到期望的结果了。
内容的提问来源于stack exchange,提问作者gs650x
相关产品推荐
相关产品推荐

