简体   繁体   English

如果对象的一侧存在具有相同键的值,则合并

[英]If there is a value with the same key on one side of the object, merge

If there is data with the same key in one of the other State Objects, I want to overwrite it.如果在其他状态对象之一中有具有相同键的数据,我想覆盖它。

Here's an example:这是一个例子:

As you can see from the code, if there are content1, content2, and the key values ​​in content1 and content2 are the same, I want to change it to the content2 coin value.从代码中可以看出,如果有content1,content2,并且content1和content2中的key值相同,我想把它改成content2的硬币值。

console.log(content1) 
[
    {
        key: 1,
        coin:0
    },
    {
        key: 2, 
        coin: 0
    },
    {
        key: 3, 
        coin: 0
    },
]
console.log(content2) 
[
    {
        key: 2,
        coin: 400
    }
]

The result I want is this:我想要的结果是这样的:

console.log(content1) 

[
    {
        key: 1,
        coin:0
    },
    {
        key: 2, 
        coin: 400
    },
    {
        key: 3, 
        coin: 0
    },
]

I've tried using the map and find functions by myself, but I can't solve it by myself, so I'm asking a question.我试过自己用map find功能,但自己解决不了,所以问个问题。

You can just use forEach method, to iterate over the content2 array, then for each item try to find it's equivalent key in the content1 array, and if there, you can update the coin directly您可以只使用 forEach 方法,遍历content2数组,然后为每个项目尝试在content1数组中找到它的等效键,如果存在,您可以直接更新硬币

 const content1 = [ { key: 1, coin:0 }, { key: 2, coin: 0 }, { key: 3, coin: 0 }, ] const content2 = [ { key: 2, coin: 400 } ] // here you loop throw the `content2` to find an item in `content1` equal it's key value. content2.forEach(item => { const itemInContent1 = content1.find(i => i.key === item.key); // if there is an item has the same key, set the coin value to the `item` value. if (itemInContent1) { itemInContent1.coin = item.coin } }) console.log(content1)

You can use Map over here to store the coins so that you don't have to loop over again and again您可以在这里使用Map来存储硬币,这样您就不必一次又一次地循环

 const arr1 = [ { key: 1, coin: 0, }, { key: 2, coin: 0, }, { key: 3, coin: 0, }, ]; const arr2 = [ { key: 2, coin: 400, }, ]; const map = new Map(); arr2.forEach(({ key, coin }) => map.set(key, coin)); const result = arr1.map(({ key, coin }) => ({ key, coin: coin + (map.get(key) ?? 0), })); console.log(result);

Reduce function can be used for this operation something like below: Reduce 函数可用于此操作,如下所示:

 let arr1 = [ { key: 1, coin: 0, }, { key: 2, coin: 0, }, { key: 3, coin: 0, }, ]; let arr2 = [ { key: 2, coin: 400, }, ]; arr1 = arr1.concat(arr2).reduce((a, b) => { let idx = a.findIndex((x) => x.key == b.key); if (idx != -1) { a.fill(b, idx, idx + 1); } else { a.push(b); } return a; }, []); console.log(arr1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM