Compare changed values in object array

Asked

Viewed 67 times

0

People need to make a comparison between two object array to be able to return a css class and tell which field was changed.

the expected result would be thus:

VALOR ANTERIOR ---------------------------------- VALOR ATUAL

name: Rafael ------------------------------------ name: Rafael

age: 29 --------------------------------------- age: 30

I’m trying to

valorAtual.find(v1 => valorAnterior.find(v2 => v2.nome == v1.nome && v2.idade != v1.idade return 'campo-alterado')). 

But the result is not as expected.

  • Opa Leo, then I need to compare two object arrays, because it will be a log record as it was before and as it was now, the arrays are coming like this: array1 [{key: rafael, value: 29}], array2 [{key: rafael, value: 30}], and on the screen I’ll put one next to the other and pass a background in the field that is with different values, so I need a logic that will return my class with the background or return empty

2 answers

0

If you need a Generic mode simply to know if there has been any change in the object, you can turn it into a String and then compare the value of the Strings, example:

JSON.stringify(valorAtual) === JSON.stringify(valorAnterior)

If this is not the case or you need some more "sophisticated" solution to the problem, please add more details and specify your problem in a clearer way.

0

You can go through the arrays and then go through each object attribute and compare the values as below. Arrays have to have the same size and objects have the same attributes, which seems to be your case.

    var array1 = [{key: 'rafael', sobrenome: 'silva', value: 29}],
    array2 = [{key: 'rafael', sobrenome: 'souza', value: 30}],
    i,
    atributo,
    size = array1.length;

    for (i = 0; i < size; i++) { // para percorrer os arrays
        for (atributo in array1[i]) { // para percorrer os atributos dos objetos dos arrays
            if (array1[i][atributo] !== array2[i][atributo]) { // comparação do valor de cada atributo
                // faz alguma coisa com as informações
                console.log(('Diferentes: ' + atributo + ': ' + array1[i][atributo] + ' - ' + array2[i][atributo]));
            }
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.