简体   繁体   English

如何比较两个对象数组并更正相同的键值?

[英]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.我正在尝试比较具有相同键的 2 个对象数组,如果 arr2 中的值不同,则更新 arr1。 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:该函数的预期结果应该是纠正 arr1 中包含val1:"cat"的对象:

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

and updated arr1 should return like this:更新后的 arr1 应该像这样返回:

{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.因此,例如,如果 arr1 中有 {val1: "big", val2: "puma"},它将通过替换 "puma" 更改为 {val1: "big", val2: "hippo"},因为值 "big"与 arr2 中的“河马”相关联。

Any ideas on how to achieve this?关于如何实现这一目标的任何想法? Thanks!谢谢!

Try below function - this will satisfy in both way for arr1尝试下面的功能 - 这将满足 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.循环遍历 arr2 项。 For each item, loop arr1 for an item with the same val1, if found: set its value to the arr2 item's value.对于每个项目,为具有相同 val1 的项目循环 arr1,如果找到:将其值设置为 arr2 项目的值。

 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.对于较大的数组,这有一些开销,因此您可能希望对 arr1 使用不同的结构(例如使用 val1 作为键),我认为这会使其简单得多。

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

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