Tengo 3 objetos, tienen una clave de "costo" que es una matriz de objetos. Como resultado, quiero tener un "principal" que permanecerá igual, excepto que su "valor" será una diferencia de este valor menos el "valor" de otros objetos
const main = { cost: [ { id: 'main', value: 20, timestapm: 'asd', current: '10'}, { id: 'main', value: 10, timestapm: 'asd', current: '10'}, { id: 'main', value: 18, timestapm: 'asd', current: '10'}, ], description: 'maindevice', total: 5 } const other = { cost: [ { id: 'device1', value: 10, timestapm: 'qwe', current: '10'}, { id: 'device1', value: 5, timestapm: 'qwe', current: '10'}, { id: 'device1', value: 9, timestapm: 'qwe', current: '10'}, ], description: 'maindevice', total: 3 } const other2 = { cost: [ { id: 'device2', value: 5, timestapm: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}, ], description: 'maindevice', total: 6 } const devices = [main, other, other2]; result i want to have => main = { cost: [ { id: 'main', value: 5, timestapm: 'asd', current: '10'}, { id: 'main', value: 3, timestapm: 'asd', current: '10'}, { id: 'main', value: 7, timestapm: 'asd', current: '10'}, ], description: 'maindevice', total: 5 }const calcNewValue = (main, other, other2) => { main.cost = main.cost.map((obj, index) => { return {...obj, value: value=other.cost[index].value - other2.cost[index].value}}) return main }esto funcionará para usted
Podría reducir los devices y mutar el primer objeto de la matriz.
const main = { cost: [{ id: 'main', value: 20, timestamp: 'asd', current: '10'}, { id: 'main', value: 10, timestapm: 'asd', current: '10'}, { id: 'main', value: 18, timestapm: 'asd', current: '10'}], description: 'maindevice', total: 5 }, other = { cost: [{ id: 'device1', value: 10, timestamp: 'qwe', current: '10'}, { id: 'device1', value: 5, timestapm: 'qwe', current: '10'}, { id: 'device1', value: 9, timestapm: 'qwe', current: '10'}], description: 'maindevice', total: 3 }, other2 = { cost: [{ id: 'device2', value: 5, timestamp: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}], description: 'maindevice', total: 6 }, devices = [main, other, other2]; devices.reduce((r, o) => { o.cost.forEach(({ value }, i) => r.cost[i].value -= value); return r; }); console.log(main); .as-console-wrapper { max-height: 100% !important; top: 0; }