用不同数组中的值更新对象的值 [英] Update value of object with values in different array

查看:47
本文介绍了用不同数组中的值更新对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有以下结构的数组: Array1:

I have two array with below structure: Array1:

[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]

Array2:

[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]

结果

Array1 =[{id:1234,name:"macaron",quantity:"330gm",rate:"300"},{id:5678,name:"Gelato",quantity:"450gm",rate:"500"}]

我希望能够用Array2中对象的速率来更新Array1中对象的唯一速率.

I want to be able to update the only rates of objects in Array1 with rate of objects in Array2.

推荐答案

如果数组的顺序或长度不同,一种有效的方法是 从Array2创建一个新比率的映射,然后从该映射循环遍历Array1蚂蚁get().

If order or lengths of the arrays are different one efficient way is create a Map of the new rates from Array2 then loop over Array1 ant get() from the Map.

这样,您只需迭代Array2一次,而不是使用像find()这样的方法的多次迭代

This way you only iterate Array2 once instead of using multiple iterations of methods like find()

let Array1=[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}],
    Array2=[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}];

const rateMap = new Map(Array2.map(({id, rate})=> [id, rate]));
Array1.forEach(e=> rateMap.has(e.id) && (e.rate = rateMap.get(e.id )))

console.log(Array1)

这篇关于用不同数组中的值更新对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆