Как сравнить погоду два массива объектов равны или нет с помощью lodsh - PullRequest
0 голосов
/ 17 июня 2020

У меня есть массив объектов, который выглядит так:

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

}

Итак, может ли кто-нибудь помочь мне с этой функцией loda sh?

Ответы [ 3 ]

1 голос
/ 17 июня 2020

С Loda sh 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 голосов
/ 17 июня 2020

Вы можете попробовать этот код, он также будет работать с глубокими объектами.

 const compareArrObjects = _.isEmpty(_.differenceWith(givenobject , values , _.isEqual))


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(compareArrObjects)
        this. values = givenobject
 }
0 голосов
/ 17 июня 2020

Вот моя функция сравнения объектов

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;
    
const obj1 = [{
 a: "10",
 b: "20"
}, {a: "30", b: "40"}, {a: "50", b: "60"}];

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

const obj3 = [{
 a: "10"
}, {a: "30", b: "40"}];

console.log('obj1 equals obj2 is', compare(obj1, obj2));

console.log('obj1 equals obj3 is', compare(obj1, obj3));

Не рекомендуется использовать JSON .stringify для сравнения объектов

...