Búsqueda de sitios web

angularjs - Equivalente de angular.equals en angular2


Estoy trabajando en la migración de un proyecto de Angular 1 a Angular 2. En el proyecto de Angular 1 estaba usando angular.equals para la comparación de objetos angular.equals($ctrl.obj1, $ctrl.newObj);, busqué en línea un método equivalente en Angular 2 pero no pude encontrar ningún resultado coincidente.

Respuesta #1

@Günter Sí, tienes razón, no hay equivalente en Angular2. Mientras buscaba más encontré la librería de terceros lodash que hará el mismo trabajo que angular.equals y la sintaxis es la misma que la de Angular, y esta librería resuelve mi problema

Ejemplo de código de la documentación de lodash

var object = { 'a': 1 };
var other = { 'a': 1 };
 
_.isEqual(object, other);
// => true
 
object === other;
// => false

Respuesta #2

Reescribí la respuesta de Ariel (¡gracias!) para que sea compatible con TSLINT. También puedes ahorrar algunos continuos usando else if, pero creo que esto es más claro. Quizás alguien más también lo necesite:

export function deepEquals(x, y) {
  if (x === y) {
    return true; // if both x and y are null or undefined and exactly the same
  } else if (!(x instanceof Object) || !(y instanceof Object)) {
    return false; // if they are not strictly equal, they both need to be Objects
  } else if (x.constructor !== y.constructor) {
    // they must have the exact same prototype chain, the closest we can do is
    // test their constructor.
    return false;
  } else {
    for (const p in x) {
      if (!x.hasOwnProperty(p)) {
        continue; // other properties were tested using x.constructor === y.constructor
      }
      if (!y.hasOwnProperty(p)) {
        return false; // allows to compare x[ p ] and y[ p ] when set to undefined
      }
      if (x[p] === y[p]) {
        continue; // if they have the same strict value or identity then they are equal
      }
      if (typeof (x[p]) !== 'object') {
        return false; // Numbers, Strings, Functions, Booleans must be strictly equal
      }
      if (!deepEquals(x[p], y[p])) {
        return false;
      }
    }
    for (const p in y) {
      if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
        return false;
      }
    }
    return true;
  }
}

Artículos relacionados