angularjs - angular.equalsin vastine angular2:ssa


Työstän Angular 1 -projektin migraatiota Angular 2:een. Angular 1 -projektissa käytin angular.equals -metodia objektien vertailuun angular.equals($ctrl.obj1, $ctrl.newObj);, etsin verkosta vastaavaa metodia Angular 2:sta, mutta en löytänyt yhtään sopivaa tulosta.

Vastaus #1

@Günter Kyllä, olet oikeassa, Angular2:ssa ei ole vastaavaa. Etsiessäni lisää löysin kolmannen osapuolen kirjaston lodash, joka tekee saman työn kuin angular.equals ja syntaksi on sama kuin Angularissa, ja tämä kirjasto ratkaisee ongelmani.

Koodiesimerkki lodash-dokumentaatiosta

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

Vastaus #2

Kirjoitin Arielin vastauksen uudelleen (kiitos!) TSLINT-yhteensopivaksi. Voit myös säästää joitain continueja käyttämällä else if:iä, mutta mielestäni tämä on selkeämpi. Ehkä joku muukin tarvitsee tätä:

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;
  }
}

Aiheeseen liittyviä artikkeleita