满足对象数组每行的数量



我有一个带有数量的数组对象。在这个数组中,我有一个键告诉我要填充的值(amountToFill)和一个键告诉我已经填充的值(amountfilling)。这个想法是指示一个数量(amount: number = 50;)和自动填充amountfill与amountToFill相同的值,但总是减少(amount: number = 50)的值,因为数组被填充是amount: number = 50等于0。

如果amountfill为>0,我们在计算总金额的减法时一定要小心。

初始结果

amountArray =[{
option:'text',
amountToFill: 5,
amountFilled:0,
},
{
option:'text1',
amountToFill: 3,
amountFilled:1,
},
{
option:'text2',
amountToFill: 10,
amountFilled:0,
},
{
option:'text3',
amountToFill: 4,
amountFilled:1,
},
{
option:'text4',
amountToFill: 4,
amountFilled:1,
},
{
option:'text5',
amountToFill: 15,
amountFilled:0,
},
{
option:'text6',
amountToFill: 5,
amountFilled:2,
},
{
option:'text7',
amountToFill:25,
amountFilled:3,
},
{
option:'text8',
amountToFill: 15,
amountFilled:0,
},
{
option:'text9',
amountToFill: 25,
amountFilled:0,
},
{
option:'text10',
amountToFill: 5,
amountFilled:0,
}];

预期的结果

amountArray1 =[{
option:'text',
amountToFill: 5,
amountFilled:5,
filled: true
},
{
option:'text1',
amountToFill: 3,
amountFilled:3,
filled: true
},
{
option:'text2',
amountToFill: 10,
amountFilled:10,
filled: true
},
{
option:'text3',
amountToFill: 4,
amountFilled:4,
filled: true
},
{
option:'text4',
amountToFill: 4,
amountFilled:4,
filled: true
},
{
option:'text5',
amountToFill: 15,
amountFilled:15,
filled: true
},
{
option:'text6',
amountToFill: 5,
amountFilled:5,
filled: true
},
{
option:'text7',
amountToFill:25,
amountFilled:12,  //amount = 0
filled: true  
},
{
option:'text8',
amountToFill: 15,
amountFilled:0,
filled: false 
},
{
option:'text9',
amountToFill: 25,
amountFilled:0,
filled: false 
},
{
option:'text10',
amountToFill: 5,
amountFilled:0,
filled: false 
}];

const amountArray =[{ option:'text', amountToFill: 5, amountFilled:0, }, { option:'text1', amountToFill: 3, amountFilled:1, }, { option:'text2', amountToFill: 10, amountFilled:0, }, { option:'text3', amountToFill: 4, amountFilled:1, }, { option:'text4', amountToFill: 4, amountFilled:1, }, { option:'text5', amountToFill: 15, amountFilled:0, }, { option:'text6', amountToFill: 5, amountFilled:2, }, { option:'text7', amountToFill:25, amountFilled:3, }, { option:'text8', amountToFill: 15, amountFilled:0, }, { option:'text9', amountToFill: 25, amountFilled:0, }, { option:'text10', amountToFill: 5, amountFilled:0, }];

let total = 50;
const res = amountArray.map(it => {
const subtract = it.amountToFill - it.amountFilled;
if (total - subtract > 0) {
total -= subtract;
return {...it, amountFilled: it.amountToFill, filled: !!total}
}
else {
const newObj = {...it, amountFilled: it.amountFilled + total, filled: !!total}
total = 0;
return newObj;
}
});

console.log(res);




相关内容

  • 没有找到相关文章

最新更新