Tengo dos matrices, cada una con un objeto de años con pares clave-valorados del año y un valor. Quiero crear una versión actualizada de array1 con los valores para los años de cada fila reducidos por los valores de los valores correspondientes en array2
es decir, A/Fred/2013 debería reducirse de 16 por 3 a 13 y así sucesivamente.
Hasta ahora lo he hecho, pero no logro actualizar la matriz correctamente.
array1.forEach(r1 => {
// Get the corresponding row from array2
let array2Record = array2.find(r2 => r2.key1 === r1.key1 && r2.key2 === r1.key2);
// Go through each of the years for this row in array1
Object.entries(r1.years).forEach(keyValuePair => {
// And reduce it by the value in array2
keyValuePair.value = keyValuePair.value - array2Record.years[keyValuePair.key].value;
})
})
Esta es la versión simplificada de los datos.
let array1 = [
{
"key1": "A",
"key2": "Fred",
"years": {
"2013": 16,
"2014": 11,
"2015": 17
}
},
{
"key1": "A",
"key2": "Jim",
"years": {
"2013": 1,
"2014": 4,
"2015": 3
}
},
{
"key1": "B",
"key2": "Mary",
"years": {
"2013": 1,
"2014": 4,
"2015": 3
}
}
]
let array2 = [
{
"key1": "A",
"key2": "Fred",
"years": {
"2013": 3,
"2014": 2,
"2015": 7
}
},
{
"key1": "A",
"key2": "Jim",
"years": {
"2013": 9,
"2014": 3,
"2015": 1
}
},
{
"key1": "B",
"key2": "Mary",
"years": {
"2013": 8,
"2014": 3,
"2015": 6
}
}
]