比较两个JavaScript对象的键

时间:2017-08-16 09:04:09

标签: javascript json compare

我有两组JavaScript对象。我想比较object1和object2,然后获取object1中所有键的列表,但不是object2中的键。我正在寻找资源来帮助我,但我最终只找到了简单对象的比较函数。我要比较的对象有很多嵌套。我在底部加了一个例子。

我如何制作比较这两个对象的功能?是否有可能创建一个灵活的函数,如果对象要更改并包含更多嵌套,它也会起作用吗?

const object1 = {
    "gender": "man",
    "age": 33,
    "origin": "USA",
    "jobinfo": {
        "type": "teacher",
        "school": "Wisconsin"
    },
    "children": [
        {
            "name": "Daniel",
            "age": 12,
            "pets": [
                {
                    "type": "cat", 
                    "name": "Willy",
                    "age": 2
                },
                {
                    "type": "dog", 
                    "name": "jimmie",
                    "age": 5
                }
            ]
        },
        {
            "name": "Martin",
            "age": 14,
            "pets": [
                {
                    "type": "bird", 
                    "name": "wagner",
                    "age": 12
                }
            ]
        }
    ],
    "hobbies": {
        "type": "football",
        "sponsor": {
            "name": "Pepsi",
            "sponsorAmount": 1000,
            "contact": {
                "name": "Leon",
                "age": 59,
                "children": [
                    {
                        "name": "James",
                        "pets": [
                            {
                                "type": "dog",
                                "age": 4
                            }
                        ]
                    }
                ]
            }
        }
    }
}

const object2 = {
    "gender": "man",
    "jobinfo": {
        "type": "teacher"
    },
    "children": [
        {
            "name": "Daniel",
            "age": 12,
            "pets": [
                {
                    "type": "cat", 
                    "name": "Willy",
                    "age": 2
                },
                {
                    "type": "dog", 
                    "name": "jimmie",
                    "age": 5
                }
            ]
        }
    ]
}

所以我想通过比较这两个对象来实现,在这种情况下,有一个数组返回,它由object1中的键组成,但不包含object2。所以数组看起来像这样。

["age", "hobbies", "type", "sponsor", "name", "sponsorAmount", "contact", "name", "age", "children", "name", "pets", "type", "age"].

这是我到目前为止所得到的。这有点工作。但它并没有打印年龄,例如,因为年龄是存在于多个嵌套对象中的属性。 jsfiddle:https://jsfiddle.net/rqdgojq2/

我看过以下资源:

3 个答案:

答案 0 :(得分:1)

使用 设置 对象和自定义getAllKeyNames()递归函数的复杂解决方案,以从指定对象获取所有唯一键名称:



var object1 = {"gender":"man","age":33,"origin":"USA","jobinfo":{"type":"teacher","school":"Wisconsin"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"jimmie","age":5}]},{"name":"Martin","age":14,"pets":[{"type":"bird","name":"wagner","age":12}]}],"hobbies":{"type":"football","sponsor":{"name":"Pepsi","sponsorAmount":1000,"contact":{"name":"Leon","age":59,"children":[{"name":"James","pets":[{"type":"dog","age":4}]}]}}}},
    object2 = {"gender":"man","age":33,"origin":"USA","jobinfo":{"type":"teacher","school":"Wisconsin"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"jimmie","age":5}]}]};
  
  function getAllKeyNames(o, res){
      Object.keys(o).forEach(function(k){
          if (Object.prototype.toString.call(o[k]) === "[object Object]") {
              getAllKeyNames(o[k], res);
          } else if (Array.isArray(o[k])) {
              o[k].forEach(function(v){
                  getAllKeyNames(v, res);
              });
          }
          res.add(k);
      });
  }
  
  var o1Keys = new Set(), o2Keys = new Set();
  getAllKeyNames(object1, o1Keys);    // unique keys of object1
  getAllKeyNames(object2, o2Keys);    // unique keys of object2
  
  // get a list of all the keys that are in object1, but not in object2
  var diff = [...o1Keys].filter((x) => !o2Keys.has(x));
  console.log(diff);
  




答案 1 :(得分:1)

感谢您的反馈。 我最终解决了这个问题,并从罗马人的回答中获得了很多灵感。

const compareObjects = (obj1, obj2)  => {
    function getAllKeyNames(o, arr, str){
        Object.keys(o).forEach(function(k){
            if (Object.prototype.toString.call(o[k]) === "[object Object]") {
                getAllKeyNames(o[k], arr, (str + '.' + k));
            } else if (Array.isArray(o[k])) {
                o[k].forEach(function(v){
                    getAllKeyNames(v, arr, (str + '.' + k));
                });
            }
            arr.push(str + '.' + k);
        });
    }

    function diff(arr1, arr2) {
        for(let i = 0; i < arr2.length; i++) {
            arr1.splice(arr1.indexOf(arr2[i]), 1);
        }
        return arr1;
    }

    const o1Keys = [];
    const o2Keys = [];
    getAllKeyNames(obj1, o1Keys, ''); // get the keys from schema
    getAllKeyNames(obj2, o2Keys, ''); // get the keys from uploaded file

    const missingProps = diff(o1Keys, o2Keys); // calculate differences
    for(let i = 0; i < missingProps.length; i++) {
        missingProps[i] = missingProps[i].replace('.', '');
    }
    return missingProps;
}

jsfiddle here:https://jsfiddle.net/p9Lm8b53/

答案 2 :(得分:0)

您可以使用对象进行计数。

&#13;
&#13;
function getCount(object, keys, inc) {
    Object.keys(object).forEach(function (k) {
        if (!Array.isArray(object)) {
            keys[k] = (keys[k] || 0) + inc;
            if (!keys[k]) {
                delete keys[k];
            }
        }
        if (object[k] && typeof object[k] === 'object') {
            getCount(object[k], keys, inc)
        }
    });
}

var object1 = { gender: "man", age: 33, origin: "USA", jobinfo: { type: "teacher", school: "Wisconsin" }, children: [{ name: "Daniel", age: 12, pets: [{ type: "cat", name: "Willy", age: 2 }, { type: "dog", name: "jimmie", age: 5 }] }, { name: "Martin", age: 14, pets: [{ type: "bird", name: "wagner", age: 12 }] }], hobbies: { type: "football", sponsor: { name: "Pepsi", sponsorAmount: 1000, contact: { name: "Leon", age: 59, children: [{ name: "James", pets: [{ type: "dog", age: 4 }] }] } } } },
    object2 = { gender: "man", jobinfo: { type: "teacher" }, children: [{ name: "Daniel", age: 12, pets: [{ type: "cat", name: "Willy", age: 2 }, { type: "dog", name: "jimmie", age: 5 }] }] },
    count = {};

getCount(object1, count, 1);
getCount(object2, count, -1);

console.log(count);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;