如何在JavaScript中比较2个对象并返回差

时间:2019-12-09 10:34:29

标签: javascript arrays node.js json javascript-objects

我有2个对象,如果对象的值不同,我想将新对象与旧对象进行比较,并返回新对象。我尝试了多种解决方案,但似乎无法实现。 这是我尝试过的

  var new_pkg ={scooter_id:"TM0060",lat:"45.747646",lng:"21.231496",alt:"99.200"};
    var old_pkg={scooter_id:"TM0060",lat:"25.747746",lng:"31.221496",alt:"100.200"};
    function difference(new_pkg, old_pkg) {
        function changes(new_pkg, old_pkg) {
            return _.transform(new_pkg, function(result, value, key) {


        if (!_.isEqual(value, old_pkg[key])) {
                result[key] = (_.isObject(value) && _.isObject(old_pkg[key])) ? changes(value, old_pkg[key]) : value;
            }
        });
    }
    return changes(new_pkg, old_pkg);
}

我想返回{lat:"45.747646",lng:"21.231496",alt:"99.200"};

3 个答案:

答案 0 :(得分:0)

您可以通过键比较对象值,如果存在差异,则返回差异对象:

var new_pkg ={scooter_id:"TM0060",lat:"45.747646",lng:"21.231496",alt:"99.200"};
var old_pkg={scooter_id:"TM0060",lat:"25.747746",lng:"31.221496",alt:"100.200"};

const getNew = (newObj, oldObj) => {
    if (Object.keys(oldObj).length == 0 
        && Object.keys(newObj).length > 0)
        return newObj;

    let diff = {};
    for (const key in oldObj) {
        if (newObj[key] && oldObj[key] != newObj[key] ) {
            diff[key] = newObj[key]; 
        }
    }

    if (Object.keys(diff).length > 0) 
        return diff;
    
    return oldObj;
}

console.log(getNew(new_pkg, old_pkg));

答案 1 :(得分:0)

它们是否始终具有相同的属性?喜欢模特吗?
如果是这样,则可以遍历其中之一并比较给定键的值。

  var new_pkg ={scooter_id:"TM0060",lat:"45.747646",lng:"21.231496",alt:"99.200"};
    var old_pkg={scooter_id:"TM0060",lat:"25.747746",lng:"31.221496",alt:"100.200"};

function getANewOneIfPropChanged(oldOne, newOne) {
  for(prop in oldOne) {
    if(oldOne[prop] !== newOne[prop]) {
      return newOne;
    }
  }
  return oldOne;
}

console.log(getANewOneIfPropChanged(old_pkg, new_pkg));

但是,实际上,根据获取新物体的规则,您可以始终使用新物体。 如果新的道具与旧的道具不同,您会选择,但是如果它们相同,那么无论您选择新的还是旧的道具都没有关系。 (除非对对象本身的引用很重要)

答案 2 :(得分:0)

尝试一下:

var new_pkg ={scooter_id:"TM0060",lat:"45.747646",lng:"21.231496",alt:"99.200"};
var old_pkg ={scooter_id:"TM0060",lat:"25.747746",lng:"31.221496",alt:"100.200"};


function compareObj(obj1, obj2) {
    // Create arrays of property names
    var obj1Props = Object.getOwnPropertyNames(obj1);
    var obj2Props = Object.getOwnPropertyNames(obj2);

    // If number of properties is different,
    // objects are not equivalent
    if (obj1Props.length != obj2Props.length) {
        return false;
    }
    
    for (var i of obj1Props) {
    	if (obj1[i] !== obj2[i]) {
      	return false;
      }
    }

    // If we made it this far, objects
    // are considered equivalent
    return true;
}

if (compareObj(old_pkg, new_pkg) === false) {
	console.log(new_pkg);
}