如何找到嵌套在数组中的对象键的diff



我有3个对象,它们有一个"成本;键,它是对象的数组。因此,我想有一个";主";其将保持不变;值";将是该值减去其他对象的差值";值";

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
}

这将为您工作

您可以减少devices并更改数组的第一个对象。

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; }

最新更新