简体   繁体   中英

How to compare two object arrays and correct identical key values?

I've searched, but haven't found precisely the trick I need.

I'm trying to compare 2 object arrays with the same keys, and update arr1 if the values in arr2 are different. Here is a codepen to play with.

let arr1 = [{val1: "dog", val2: "friendly"},{val1: "cat", val2: "fluffy"}]

let arr2 = [{val1: "cat", val2: "evil"},{val1: "mouse", val2: "tiny"},{val1: "hippo", val2: "big"}]

Expected result of the function should be correcting the object including val1:"cat" in arr1:

 {val1: "cat", val2: "fluffy"} ----->  {val1: "cat", val2: "evil"}

and updated arr1 should return like this:

{val1: "dog", val2: "friendly"}, { val1: "cat", val2: "evil"}

Trick is, the code should also work both ways. So for example if there is {val1: "big", val2: "puma"} in arr1, it would change to {val1: "big", val2: "hippo"} by replacing "puma", since value "big" is linked to "hippo" in arr2.

Any ideas on how to achieve this? Thanks!

Try below function - this will satisfy in both way for arr1

function validateArray() {
        arr2.forEach(function(arr2Element) {
            arr1.forEach(function(arr1Element) {
                if (arr2Element.val1 === arr1Element.val1) {
                    arr1Element.val2 = arr2Element.val2;
                } else if (arr2Element.val2 === arr1Element.val1) {
                    arr1Element.val2 = arr2Element.val1;
                }
            });
        });
        console.log(arr1);
    }

Loop through arr2 items. For each item, loop arr1 for an item with the same val1, if found: set its value to the arr2 item's value.

 let arr1 = [ { val1: "dog", val2: "friendly" }, { val1: "cat", val2: "fluffy" } ]; let arr2 = [{ val1: "cat", val2: "evil" }, { val1: "mouse", val2: "tiny" }, { val1: "hippo", val2: "big" } ]; function validate() { arr2.forEach(function(v2) { arr1.forEach(function(v, idx) { if (v2.val1 == v.val1) { console.log('Change', v.val2, 'to', v2.val2); arr1[idx].val2 = v2.val2; } }); }); }
 <button id="validate" onclick="validate()"> Validate </button>

For larger arrays this has some overhead, so you might want to use a different structure for arr1 (like using val1 as the key), which would make it a lot simpler I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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