简体   繁体   English

如何比较两个对象

[英]How to compare two objects

I have a scenario, where I have two different Objects. 我有一个场景,其中有两个不同的对象。

Scenario to achieve: 实现方案:

From two objects I need to match the values which has "A1","B2", etc... 从两个对象中,我需要匹配具有“ A1”,“ B2”等的值。

Since both the objects values are not in proper order, the loop is breaking and missing some values. 由于两个对象值的顺序都不正确,因此循环中断并丢失了一些值。

In my demo the object1 has same repeated value ie "C3", It should be displayed only once. 在我的演示中,object1具有相同的重复值,即“ C3”,应该仅显示一次。

Final output required is I need to detect only the matched values from two objects and display its corresponding "a" and "b values." 所需的最终输出是,我只需要检测两个对象中匹配的值并显示其相应的“ a”和“ b值”。

I have tried almost 90%, but somewhere some minor error is breaking my loop, Please help me out. 我已经尝试了将近90%,但在某个小错误使我的循环中断的地方,请帮帮我。

Sample code: 样例代码:

for(var i=0;i<obj1.results[0].loc.length;i++){
    var findA = obj1.results[0].loc[i].anc[0].title;
    for(var j=0;j< obj2.ILoc.length;j++){
        var findB = obj2.ILoc[j].ais;
        if(findA == findB) {
            var a = obj1.results[0].loc[i].a;
            var b = obj1.results[0].loc[i].b;
            console.log(a);
            console.log(b);
        }       
    }
}

This is what I have tried: Demo Link 这是我尝试过的: 演示链接

I would recommend using for...in loop, since you're using objects instead of arrays. 我建议使用for ... in循环,因为您使用的是对象而不是数组。

for (variable in object) {...
}

If length property of both objects is equal, then this kind of loop alone will help you to compare objects with ease. 如果两个对象的length属性相等,那么单独使用这种循环将有助于您轻松比较对象。

I would recommend using the diff module . 我建议使用diff模块 You can use it in node.js and the browser. 您可以在node.js和浏览器中使用它。

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

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