我不确定我是否能正确地解释这一点,但它是这样的。比如这里是:
List = {
0: {
payment: 1,
value: 10
},
1: {
payment: 2,
value: 15
},
2: {
payment: 1,
value: 12
},
3: {
payment: 2,
value: 13
}
}
如何分别将两笔付款的值相加?又称sumforpayment1= 10 +12
和sumforpayment2= 15 + 13
您可以使用Object.keys()
和reduce()
来返回每次付款的总和。
var data = {
0: {
payment: 1,
value: 10
},
1: {
payment: 2,
value: 15
},
2: {
payment: 1,
value: 12
},
3: {
payment: 2,
value: 13
}
}
var result = Object.keys(data).reduce(function(r, e) {
var key = 'sumforpayment' + data[e].payment;
r[key] = (r[key] || 0) + data[e].value;
return r;
}, {})
console.log(result)
我认为你需要一个对象数组。在这种情况下,对象是不必要的。
List = [
{
payment: 1,
value: 10
},
{
payment: 2,
value: 15
},
{
payment: 1,
value: 12
},
{
payment: 2,
value: 13
}
];
var List2 = {};
List.map(function(o) {
if(!List2['sumforpayment' + o.payment]) {
List2['sumforpayment' + o.payment] = o.value;
}
else {
List2['sumforpayment' + o.payment] += o.value;
}
});
console.log(List2);
</script>
这些天我喜欢这个符号迭代器的东西,当它涉及到对象。
var list = {
0: {
payment: 1,
value: 10
},
1: {
payment: 2,
value: 15
},
2: {
payment: 1,
value: 12
},
3: {
payment: 2,
value: 13
}
},
res = [];
list[Symbol.iterator] = function*(){
var oks = Object.keys(this),
payment = {1:0,2:0};
for (var key of oks) this[key].payment === 1 ? payment["1"] += this[key].value
: payment["2"] += this[key].value;
yield payment;
};
res = [...list];
console.log(res);
首先,请修改您的JavaScript对象,因为它没有正确格式化。
属性之间用逗号分隔。
您可以创建一个实用程序函数,该函数遍历您的对象,搜索支付标识值并计算总金额。
如何工作:
- 使用
Object.keys()
迭代你的对象属性。 - 如果属性
payment
的值传递了"选择器" (paymentNumber
) - 将其值相加,返回结果的总金额。
var list = {
0: {
payment: 1,
value: 10
},
1: {
payment: 2,
value: 15
},
2: {
payment: 1,
value: 12
},
3: {
payment: 2,
value: 13
}
}
var calculatePaymentSum = function(paymentNumber, data) {
var result = 0;
Object.keys(data).forEach(function(key) {
if (data[key].payment === paymentNumber) {
result += data[key].value;
}
}, this);
return result;
};
console.log('sum of payment 1 = ', calculatePaymentSum(1, list));
console.log('sum of payment 2 = ', calculatePaymentSum(2, list));