gpt4 book ai didi

javascript - jQuery 对象 : summing all instances of value A where value B is duplicate

转载 作者:行者123 更新时间:2023-12-02 15:33:54 25 4
gpt4 key购买 nike

我有这个增值税值对象:

[
{
"code": "2",
"rate": "17.5%",
"net": 0
},
{
"code": "2",
"rate": "17.5%",
"net": 0
},
{
"code": "1",
"rate": "Zero Rated",
"net": 0
},
{
"code": "1",
"rate": "Zero Rated",
"net": 0
},
{
"code": "4",
"rate": "20%",
"net": 304.7
},
{
"code": "1",
"rate": "Zero Rated",
"net": 0
},
{
"code": "4",
"rate": "20%",
"net": 1200.24
},
{
"code": "4",
"rate": "20%",
"net": 5201.04
},
{
"code": "4",
"rate": "20%",
"net": 1258.82
},
{
"code": "4",
"rate": "20%",
"net": 629.41
},
{
"code": "4",
"rate": "20%",
"net": 629.41
}
]

我想要做的是显示所有单独的代码及其各自值的总和,即我想将增值税代码为1的所有净值相加并显示它(代码,费率和总净值),然后单独显示其中增值税代码为 2 等。

我尝试使用 $.each,创建一个新对象并比较两个对象,然后添加值或创建一个代码相等的新实例,但它变得困惑和困惑:

var vatAnalysisItem = [];

$.each(self.vat(), function(index) {
$.each(self.vat()[index], function(key1, value1) {
if(key1 == "code") {
if(vatAnalysisItem.length === 0) {
vatAnalysisItem.push({code: self.vat().code, rate: self.vat().rate, net: self.vat().net});
}
else {
$.each(vatAnalysisItem, function(key2, value2) {
if(key2 == "code")
if(value in vatAnalysisItem) {
vatAnalysisItem[net] += self.vat().net;
}
else {
vatAnalysisItem.push({code: self.vat()[code], rate: self.vat().rate, net: self.vat().net});
}
});
}
}
});
});

。我不知道该怎么做。我将使用 Knockout JS 在 View 中显示完整的值。

任何帮助将不胜感激!

最佳答案

排序顺序可能有误,请根据口味进行调整。

var vm = {
data: ko.observableArray([]),
cumulativeData: ko.pureComputed(function() {
var result = {};
vm.data().forEach(function(datum) {
var cumul = result[datum.code];
if (!cumul) {
result[datum.code] = cumul = {
code: datum.code,
rate: datum.rate,
net: 0
};
}
cumul.net += datum.net;
});
return Object.keys(result).sort().map(function(code) { return result[code]; });
})
};

ko.applyBindings(vm);

var newData = [{"code":"2","rate":"17.5%","net":0},{"code":"2","rate":"17.5%","net":0},{"code":"1","rate":"Zero Rated","net":0},{"code":"1","rate":"Zero Rated","net":0},{"code":"4","rate":"20%","net":304.7},{"code":"1","rate":"Zero Rated","net":0},{"code":"4","rate":"20%","net":1200.24},{"code":"4","rate":"20%","net":5201.04},{"code":"4","rate":"20%","net":1258.82},{"code":"4","rate":"20%","net":629.41},{"code":"4","rate":"20%","net":629.41}];
vm.data(newData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table data-bind="foreach: cumulativeData">
<tr>
<td data-bind="text: code"></td>
<td data-bind="text: rate"></td>
<td data-bind="text: net"></td>
</tr>
</table>

关于javascript - jQuery 对象 : summing all instances of value A where value B is duplicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33099801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com