Checking for equality between objects

2

Well, I need to check the contents of 2 objects, I need to know if they are the same or not in the main fields.

My idea is to check when inserting some data in the localStorage if that data already exists, if there is I should replace the existing object in the array of locaStorage, if not I need to create.

Example:

Object1 {TXT_NOMEX_PESSO: "Renan Rodrigues Moraes", COD_IDENT_PESSO: "9999160307115906859", FLG_IDENT_PESSO: "L", FLG_STATU_PESSO: "A", FLG_STATU_PARTC: "A"…}

Object2 {TXT_NOMEX_PESSO: "Lidiane Morais", COD_IDENT_PESSO: "9999160307134108952", FLG_IDENT_PESSO: "L", FLG_STATU_PESSO: "A", FLG_STATU_PARTC: "A"…}

Object3 {TXT_NOMEX_PESSO: "Renan Rodrigues", COD_IDENT_PESSO: "9999160307115906859", FLG_IDENT_PESSO: "L", FLG_STATU_PESSO: "A", FLG_STATU_PARTC: "A"…}

If I enter the Object1 and soon after the Object2 it would enter normal, because there would be no, if I inserted the Object3 it should replace the Object1 with the Object3 .

I need to do this as simply as possible, if any. The method I know to do this is to go through each tuple of chave : valor and check whether it is the same or not.

I forgot to tell you something very important, as this is all about localStorage I need to know if it exists or not, that is, I am not always sure that I will have 2 objects equal.

    
asked by anonymous 18.05.2016 / 13:48

2 answers

1

You can iterate all fields of the first object and verify that the value of these fields matches to the same field value in the second object.

function compareObjetos(objA, objB) {
    if (objA == null || objB == null) {
        // Se um dos objetos é nulo então são objetos diferentes. 
        // Mesmo por que null nem mesmo é um objeto...
        return false;
    }

    for (prop in objA) {
        if(!(objB[prop] === objA[prop])) {
            // Os objetos são diferentes.
            return false;
        }
    }

    // Os objetos são equivalentes.
    return true;
}
    
18.05.2016 / 13:57
1

The easiest way is to transform each of the objects into strings and compare them:

JSON.stringify(obj1) === JSON.stringify(obj2);

Source: link

EDIT: Since the problem involves LocalStorage , I suggest the following solution:

function saoIguais(nomeObj1, nomeObj2) {
    var obj1 = localStorage.getItem(nomeObj1)
    var obj2 = localStorage.getItem(nomeObj2)
    return obj1 !== null && obj2 !== null && JSON.stringify(obj1) === JSON.stringify(obj2)
}
    
18.05.2016 / 13:52