我想知道如何在javascript中更新对象数组。
如何使用示例对象作为函数的参数发送来更新original_sample并执行如图所示的计算
在这里,如何在单个函数中执行不同的计算<app-card>
<h2>New child I passed</h2>
<p>And another one</p>
</app-card>
和with payfee
并更新对象
Gotstuck及其在javascript中的操作。
without payfee
// update the original_sample with sample2 values
var res = getValue(original_sample, sample2);
// update the original_sample with sample3 values
var res = getValue(original_sample, sample3);
function getValue(original, sample){
return original.map(({ fee, rate, ...others }) => ({
id: 'trans'
amount: amount,
fee: +fee,
rate: +rate,
targetamount: (amount-fee)*rate
}))
}
//inputs
var original_sample= [{
id: "trans",
fee: 1,
rate: 2.2,
amount:100,
}]
//passed as input to update original_sample
var sample2 = [{
id: "trans",
fee: 2,
rate: 4.0,
payfee: 1%,
amount: 100,
}]
//passed as input to update original_sample
var sample3 =[{
id: "trans",
fee: 1,
rate: 1.0,
amount: 100
}]
答案 0 :(得分:0)
由于每个数组中只有一个对象,因此我要么完全放弃使用数组,要么在每次需要做的事情时都提取对象。例如这样的
function getValue(orig, update) {
var obj = orig[0] = Object.assign({}, update[0]);
if ("payfee" in obj) obj.payfee = parseInt(obj.payfee);
obj.targetamount = (obj.amount-obj.fee) * (1 - (obj.payfee||0)/100) * obj.rate;
}
// Demo:
var original_sample = [{id: "trans", fee: 1, rate: 2.2, amount:100}];
var sample2 = [{id: "trans", fee: 2, rate: 4.0, payfee: "1%", amount: 100}];
var sample3 = [{id: "trans", fee: 1, rate: 1.0, amount: 100}];
getValue(original_sample, sample2);
console.log(original_sample);
getValue(original_sample, sample3);
console.log(original_sample);
答案 1 :(得分:0)
使用Array.concat()
合并数组,然后将合并后的数组简化为一个对象,方法是始终获取具有相同id
的最后一个对象并计算targetAmount
。用Object.values()
转换回数组。
const getValue = (original, sample) =>
Object.values(
original.concat(sample)
.reduce((r, o) => ({
...r,
[o.id]: {
...o,
targetamount: (o.amount - o.fee) * o.rate
}
})
, {})
)
const original_sample = [{"id":"trans","fee":1,"rate":2.2,"amount":100}]
const sample2 = [{"id":"trans","fee":2,"rate":4,"payfee":0.01,"amount":100}]
const sample3 = [{"id":"trans","fee":1,"rate":1,"amount":100}]
const originalAnd2 = getValue(original_sample, sample2)
const original2And3 = getValue(originalAnd2, sample3)
console.log(originalAnd2);
console.log(original2And3);