Home > front end >  If there is a value with the same key on one side of the object, merge
If there is a value with the same key on one side of the object, merge

Time:07-15

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.

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.

CodePudding user response:

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

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)

CodePudding user response:

You can use Map over here to store the coins so that you don't have to loop over again and again

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);

CodePudding user response:

Reduce function can be used for this operation something like below:

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);

  • Related