英文:
Summing all numbers from JSON API response in Angular
问题
我需要帮助将来自API响应的JSON中的所有数字相加,并将它们保存在一个变量中,以便我可以在模板中输出...
这是我得到的JSON的样子:
[
{
"count": 495,
"label": "Ticket",
"user_id": "42807"
},
{
"count": 248,
"label": "Hotel",
"user_id": "42807"
},
{
"count": 75,
"label": "Insurance",
"user_id": "42807"
}
]
这是我在组件的component.ts文件中从服务获取数据的方式:
noOfPurchases: number;
getSingleCustomerPurchases() {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.customerService.getSingleCustomerPurchases(id).subscribe(
data => {
this.purchasedProd = data;
// console.log(this.purchasedProd);
},
error => {
console.log('Error', error);
});
}
我尝试使用.map
函数,但我得到了错误信息“属性'map'在类型'number'上不存在”。如何将所有“count”的数字相加呢?
英文:
I need help summing all the numbers from JSON that I get from an API response and saving them in a variable that I can output in template...
This is what my JSON that I get looks like:
[
{
"count": 495,
"label": "Ticket",
"user_id": "42807"
},
{
"count": 248,
"label": "Hotel",
"user_id": "42807"
},
{
"count": 75,
"label": "Insurance",
"user_id": "42807"
},
]
This is how I'm getting the data from service in my component.ts file:
noOfPurchases: number;
getSingleCustomerPurchases() {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.customerService.getSingleCustomerPurchases(id).subscribe(
data => {
this.purchasedProd = data;
// console.log(this.purchasedProd);
},
error => {
console.log('Error', error);
});
}
I have tried using .map function but I was getting the error Property 'map' does not exist on type 'number'. How would I go about summing all the numbers of "count" together?
答案1
得分: 1
你可以使用 reduce 数组方法:
this.purchasedProd = data.reduce((acc, curr) => acc += curr.count, 0)
英文:
You can use reduce array method
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
this.purchasedProd = data.reduce((acc, curr) => acc += curr.count, 0)
答案2
得分: 1
在你的组件中声明一个你想在模板中使用的变量:
public countSum:number = 0;
然后在订阅中这样使用它:
getSingleCustomerPurchases() {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.customerService.getSingleCustomerPurchases(id).subscribe(
data => {
this.purchasedProd = data;
this.countSum = 0;
this.purchasedProd.forEach(value => this.countSum += value.count);
},
error => {
console.log('Error', error);
});
}
英文:
In your's component declare a variable which you would like to use in template
public countSum:number = 0
Then in the subscription you do it like that:
getSingleCustomerPurchases() {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.customerService.getSingleCustomerPurchases(id).subscribe(
data => {
this.purchasedProd = data;
this.countSum = 0;
this.purchasedProd.forEach(value => this.countSum += value.count)
},
error => {
console.log('Error', error);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论