如何使用lodsh比较两个对象的数组是否相等

问题描述 投票:0回答:2

我有一个看起来像的对象数组,

let givenobject = [{
 a: "10",
 b: "20"
}, {a: "30", b: "40"}, {a: "50", b: "60"}]

现在,我有一个observable,它是

@observable values = {}

现在,单击时会触发一个函数,它将将此对象数组分配给可观察对象。

setAction(givenobject) {

 //Here I am trying to check wheather the coming object is same as that of previous(which is the observable) if both are same then do not update or else update.

 if(givenobject !== values)
    this. values = givenobject

}

所以,有人可以使用此lodsh功能帮助我吗?

javascript reactjs lodash
2个回答
0
投票

使用Lodash https://lodash.com/docs/4.17.15#isEqual

var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false

没有:var isEqual = JSON.stringify(object1) == JSON.stringify(object2)


0
投票

这是我的对象比较功能

const compare = (obj1, obj2) =>
  Array.isArray(obj1)
    ? Array.isArray(obj2) && obj1.length === obj2.length && obj1.every((item, index) => compare(item, obj2[index]))
    : obj1 instanceof Date
    ? obj2 instanceof Date && obj1.getDate() === obj2.getDate()
    : obj1 && typeof obj1 === 'object'
    ? obj2 && typeof obj2 === 'object' &&
      Object.getOwnPropertyNames(obj1).length === Object.getOwnPropertyNames(obj2).length &&
      Object.getOwnPropertyNames(obj1).every(prop => compare(obj1[prop], obj2[prop]))
    : obj1 === obj2;

使用JSON.stringify比较对象不是一个好习惯

© www.soinside.com 2019 - 2024. All rights reserved.