返回两个嵌套对象之间的差异

时间:2018-08-01 14:51:50

标签: javascript

我有两个对象,我想编写一个返回对象的方法(最好是找到一个库),这是这两个对象之间的区别,所以具有:

const sourceObject = {
  name: 'John Doe',
  address: {
    city: 'Zurich',
    registered_date: '2018-08-10',
    residents: [
      { id: 1, name: 'Amanda', phones: ['500600500', '500400300'] },
      { id: 2, name: 'Travis', phones: [] },
    ],
  },
  partner: {
    name: 'Clara Doe',
  },
  interests: ['valleys', 'oceans', 'hawaii'],
  phone_model: 'iPhone X',
};

const compareToObject = {
  name: 'John Doe-Manny',
  address: {
    city: 'Zurich',
    registered_date: '2019-08-10',
    residents: [
      { id: 1, name: 'Amanda', phones: ['500400300', '100200300'] },
    ],
  },
  partner: undefined,
  interests: ['valleys'],
  phone_model: undefined,
};

结果是:

const expectedResult = {
  name: 'John Doe-Manny',
  address: {
    registered_date: '2019-08-10',
    residents: [
      { id: 1, phones: ['500400300', '100200300'] },
      { id: 2, deleted: true }, // See how deleted objects are handled
    ],
  },
  partner: undefined,
  phone_model: undefined,
};

我正在尝试找到一种方法或找到一个库,但是我从未如此失败。我讨厌递归。

1 个答案:

答案 0 :(得分:1)

我发现这个问题很有趣,所以我想解决一下。不幸的是,我现在不能再花时间在上面,所以也许其他人可以继续做下去。 :-)

const sourceObject = {
  name: 'John Doe',
  address: {
    city: 'Zurich',
    registered_date: '2018-08-10',
    residents: [
      { id: 1, name: 'Amanda', phones: ['500600500', '500400300'] },
      { id: 2, name: 'Travis', phones: [] },
    ],
  },
  partner: {
    name: 'Clara Doe',
  },
  interests: ['valleys', 'oceans', 'hawaii'],
  phone_model: 'iPhone X',
};

const compareToObject = {
  name: 'John Doe-Manny',
  address: {
    city: 'Zurich',
    registered_date: '2019-08-10',
    residents: [
      { id: 1, name: 'Amanda', phones: ['500400300', '100200300'] },
    ],
  },
  partner: undefined,
  interests: ['valleys'],
  phone_model: undefined,
};


var symb = 2039432423532453;//use symbol if supported

function diff(source, comp){
    if(! ['object', 'array'].includes(typeof(comp))){
        if(source !== comp){
            return comp;
        }
        return symb;
    }
    var out = {};
    for(var k in comp){
        var res = diff(source[k], comp[k]);
        if(res !== symb){
            out[k] = res;
        }
    }
    if(Object.keys(out).length != 0)
      return out;
    return symb;
}

console.log(diff(sourceObject, compareToObject));