对象之间的Javascript差异

时间:2017-12-10 07:46:25

标签: javascript

我试图在我的html中显示一个显示CRUD日志的表。我的php脚本在UPDATE之前和之后选择并存储对象,并将json对象保存到表中。这就是我的html表格:

enter image description here

我试图通过比较2个对象并找到不匹配然后在表名中显示的对象来显示更改的内容:旧值和名称:可读视图中的新值..这是我的功能(没有回报)

$scope.parsehistory = function(old, neww) {
       try {

    var o1 = JSON.parse(old),
        o2 = JSON.parse(neww);



    var old_value = _.omit(o1, function(v, k) {
        return o2[k] === v;
    });

    const new_value = Object.keys(old_value).reduce((accumulator, key) => {
        accumulator[key] = o2[key];
        return accumulator;
    }, {});

    var length = Object.keys(old_value).length;
    var keys = Object.keys(old_value);

    console.log("length:", length);
    for (i = 0; i < length; i++) {
        var name = keys[i];

        var oldvaluee = old_value[name];
        var newvaluee = new_value[name];
        var valuechanged = name;
        console.log("newval", newvaluee);
        console.log("oldval", oldvaluee);
        console.log("valuechanged", valuechanged);
        //studyCrudlog=function(uid,original_value,new_value,description,componant_name,study_id)
        //AppStorage.studyCrudlog($scope.newuser.users_id,oldvaluee,newvaluee,(valuechanged + " value changed."),"Users",AppStorage.getStudy().id);
    }
} catch (ex) {
    console.log(ex);
  }
}

以下是

的结果
  

console.log(&#34; newval&#34;,newvaluee);               console.log(&#34; oldval&#34;,oldvaluee);               console.log(&#34; valuechanged&#34;,valuechanged);

enter image description here

在这种情况下,差异将是numberid和sitename

任何帮助都将受到高度赞赏!

2 个答案:

答案 0 :(得分:1)

您的实施几乎已接近,您只需使用omitBy

_.omit  接受string[],它基本上删除了数组中指定的任何键。

_.omitBy  接受一个回调,其中相应地过滤属性并进行更多控制。

const o1 = {sitename: "newValue", numberid: "newValue", id: "28"};

const o2 = {sitename: "newValue33", numberid: "newValue33", id: "28"};

const oldValue = _.omitBy(o1, (v, k) => o2[k] === v)

console.log(oldValue);

const newValue = Object.keys(oldValue).reduce((a, b) => { a[b] = o2[b]; return a;}, {})

console.log(newValue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

答案 1 :(得分:0)

请看这段代码。假设对象具有相同的结构,它将给出更改值的列表。

    /*Checks if objects are same*/
function isObjectsSame(a, b) {
  var objStringA = JSON.stringify(a),
    objStringB = JSON.stringify(b);

  return (objStringA == objStringB);
}

function objDiff(a, b) {
  var isSame = isObjectsSame(a, b);
  var changeTracker = [];
  if (isSame) {
    console.log('Objects are equal.No values changed');
  } else {
    var keys = Object.keys(a),
      key;
    for (var i = 0; i < keys.length; i++) {
      key = keys[i];
      if (a[key] != b[key]) {
        changeTracker.push({ //Captures the difference.
          key: key,
          value: [a[key], b[key]]
        })
      }
    }

    console.log(changeTracker); // Prints the difference
  }
}

请将您的对象传递给函数objDiff(obj1,obj2);