【问题标题】:Object comparison based on keys基于键的对象比较
【发布时间】:2015-03-18 05:59:20
【问题描述】:

我正在尝试仅通过 KEYS 比较对象。

var obj1 = [ {"depid": "100", "depname": ""}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ];
var obj2 = [ {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}}, {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"} ];

例如,如果我们比较 obj1 中的对象 {"depid": "100", "depname": ""} 与 obj2 {"depid": "100", "depname": "role"},必须返回 true。 因为钥匙是一样的。我需要在 obj1 中设置 obj2 的值。

//Expected result
obj1 = [ {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ]

I have tried the solution provided in this link 但仍然无法仅在对象键上进行比较并将值从 obj2 更新为 obj1

【问题讨论】:

  • 真正的问题是什么?
  • 这不是 JSON,它只是一个 POJO(普通的旧 JavaScript 对象)。
  • 提供的链接无效

标签: javascript object


【解决方案1】:

此函数检查:对于 obj1 中的每个对象,它将查找 obj2 中的每个键。因此它正在检查 obj2 中是否存在 deptid,如果存在则返回 true。如果

var f = function(obj1, obj2){
    console.log('Starting...', obj1.length);
    for(var i in obj1){
        var memberObj1 = obj1[i];
        var memberObj1Keys = Object.keys(memberObj1);
        console.log('Keys in each object', memberObj1Keys);
        // console.log('Checking for ', memberObj1);
        for(var j in obj2){
            var memberObj2 = obj2[j];
            console.log('Object2 ', memberObj2);
            for(var eachKey in memberObj1Keys){
                console.log('Looking for %s in obj2', memberObj1Keys[eachKey]);
                if(memberObj2[memberObj1Keys[eachKey]]){
                    console.log('Found');
                    return true;
                }
            }
        }
        console.log('======================');
    }
 return false;
}

使用函数。

var result = f(obj1, obj2);
console.log(result);

这是针对您的问题的快速实施。到目前为止,我还没有尝试优化循环。

欢迎任何编辑。

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2021-10-15
    • 2016-09-07
    相关资源
    最近更新 更多