我有 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
}
uj5u.com熱心網友回復:
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
}
這對你有用
uj5u.com熱心網友回復:
您可以減少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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/350218.html
標籤:javascript 数组 目的
上一篇:為什么我會在pytest-qt中收到這個“包裝的C/C 物件......已被洗掉”的錯誤?
下一篇:我需要xpath的解決方案
