How to compare indexes of two objects and return what is different?

3

I would like to compare these two objects and return the index that is different.

In this case it is to return the 4th of the second object (it will always be different in the second).

var arr = {
   1 : 'Corsa',
   2 : 'Ka',
   3 : 'Pálio'
};

var foo = {
   1 : 'Corsa',
   2 : 'Ka',
   3 : 'Pálio',
   4 : 'Jeep'
};

How do I do this in JavaScript or using jQuery?

    
asked by anonymous 26.01.2017 / 14:17

3 answers

3

For objects, you can do as follows:

Object.defineProperty(Object.prototype, "except", {
  enumerable: false,
  value: function (outro)  {
    var keysB = Object.keys(outro);
    return Object.keys(this).reduce(function (resultado, key) {
      if (keysB.indexOf(key) == -1)
        resultado[key] = this[key];
      return resultado;
    }.bind(this), {});
  }
});

var foo = {
  1 : 'Corsa',
  2 : 'Ka',
  3 : 'Pálio'
};

var bar = {
  1 : 'Corsa',
  2 : 'Ka',
  3 : 'Pálio',
  4 : 'Jeep'
};

console.log(bar.except(foo));
    
26.01.2017 / 15:00
2

Another way is to convert the object to string and save it to an array. In this case, even if the size of the objects is uncertain, in case the first one is larger than the second, it will work.

var arr = {
  1: 'Corsa',
  2: 'Ka',
  3: 'Pálio'
};

var foo = {
  1: 'Corsa',
  2: 'Ka',
  3: 'Pálio',
  4: 'Jeep'  
};

var obj1 = JSON.stringify(arr).replace(/{|}/g, '').split(",");
var obj2 = JSON.stringify(foo).replace(/{|}/g, '').split(",");
var maior = Math.max(obj1.length, obj2.length);

for (var i = 0; i < maior; i++) {
  if (obj1.length > obj2.length) {
    if (obj1[i] != obj2[i]) {
      console.log("índice diferente: " + obj1[i].split(":")[0] + " entre os objs");
      break;
    }
  } else {
    if (obj2[i] != obj1[i]) {
      console.log("índice diferente: " + obj2[i].split(":")[0] + " entre os objs");
      break;
    }
  }
}
    
26.01.2017 / 15:18
1

You need to know which object has the most keys, and then iterate until you find a key that the other does not have. You can do it like this:

function comparar(a, b) {
    var axb = Object.keys(a).length > Object.keys(b);
    var mairObjeto = axb ? a : b;
    var menorObjeto = axb ? b : a;

    for (var i in mairObjeto) {
        if (!menorObjeto.hasOwnProperty(i)) return i
    }
}

An example would look like this:

var foo = {
    1: 'Corsa',
    2: 'Ka',
    3: 'Pálio'
};

var bar = {
    1: 'Corsa',
    2: 'Ka',
    3: 'Pálio',
    4: 'Jeep'
};

function comparar(a, b) {
    var axb = Object.keys(a).length > Object.keys(b);
    var mairObjeto = axb ? a : b;
    var menorObjeto = axb ? b : a;

    for (var i in mairObjeto) {
        if (!menorObjeto.hasOwnProperty(i)) return i
    }
}

console.log(comparar(foo, bar));
    
26.01.2017 / 18:10