Skip to content
Advertisement

I want to compares the difference between two objs but ignore some key

I’m using Lodash to compare two objects returned from Postman but I want to ignore the dynamic values (page_view and deletion.update_time). How can I do this? I’ve tried passing in the property names into omit but it’s not working… how can I resolve this issue? Thank you.

var obj1 = {
  name: "James",
  age: 17,
  page_view: "2",
  creation: "13-03-2016",
  deletion: {
    "article_id": 4469568,
    "update_time": 1226,
  }
}
var obj2 = {
  name: "James",
  age: 17,
  page_view: "62",
  creation: "13-03-2016",
  deletion: {
    "article_id": 4469568,
    "update_time": 12265,
  }
}

var result = _.isEqual(
  _.omit(obj1, ['page_view', 'update_time']),
  _.omit(obj2, ['page_view', 'update_time'])
);
if (!result) {
  pm.expect.fail("Pro and Sta are different")
}

Advertisement

Answer

You need to specify this on the sub-object:

var obj1={name:"James",age:17,page_view:"2",creation:"13-03-2016",deletion:{"article_id":4469568,"update_time":1226,}}
var obj2={name:"James",age:17,page_view:"62",creation:"13-03-2016",deletion:{"article_id":4469568,"update_time":12265,}}

const stripDynamicValues = o => {
  let toCompare = _.omit(_.cloneDeep(o), "page_view");
  // Here, you need to work explicitly on the sub-object
  toCompare.deletion = _.omit(toCompare.deletion, "update_time");
  return toCompare;
};

var result = _.isEqual(stripDynamicValues(obj1), stripDynamicValues(obj2));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement