angular - 如何通过属性对数组中的对象求和?
问题描述
我想在我的数组中有 2 个级别,但我不知道该怎么做。
有我的初始化数组:
this.users = response["users"];
this.users = JSON.parse(JSON.stringify(this.users));
this.technos = response["technos"];
this.technos = JSON.parse(JSON.stringify(this.technos));
for(let z in this.technos){
for (let i in this.users){
for( let x in this.users[i].techno){
if(this.users[i].techno[x].name == this.technos[z].name){
this.dataUsers.push(this.users[i].techno[x]);
}
}
}
给我这个:
[
{
"name": "java",
"niveau": 3
},
{
"name": "java",
"niveau": 1
},
{
"name": "html",
"niveau": 5
},
{
"name": "html",
"niveau": 4
}
]
我试图这样做,但它不是我预期的结果:
for(let k in this.dataUsers){
if(this.dataUsers[k].name == this.technos[z].name){
this.dataNiveau[this.technos[z].name] = 0;
this.dataNiveau[this.technos[z].name] += this.dataUsers[k].niveau;
console.log(this.dataNiveau);
}
}
}
结果:
Array []
html: 4
java: 1
length: 0
总和没有用。
有人知道我该怎么做吗?
解决方案
Not sure if this is what you want. Check the solution.
const dataUsers = [{
"name": "java",
"niveau": 3
}, {
"name": "java",
"niveau": 1
}, {
"name": "html",
"niveau": 5
}, {
"name": "html",
"niveau": 4
}]
const sum = {};
for (let item of dataUsers) {
if (sum[item.name]) {
sum[item.name] += item.niveau
} else {
sum[item.name] = item.niveau
}
}
console.log('sum----', sum)
推荐阅读
- laravel - 如何设置重写规则以使用 apache 在同一服务器中转到前端和后端
- typescript - Typescript - 从 yaml 读取变量并用它们替换另一个文件中的标记
- typescript - 如何键入传入函数的窄数组类型?
- flutter - 推送扩展的 Widget Flutter
- python - 如何在 python 中检查 Outlook ActiveWindow 的 TypeName
- sql - 根据另一列中的值何时更改添加新列
- java - DocuSign : 未经用户同意登录
- javascript - 如何使 NodeJS + ExpressJS API 防弹?
- java - 由于空值无法返回。java.lang.NullPointerException:无法调用“reactor.core.publisher.Mono.map”,因为为空
- java - 如何在 Spring/HTML 中创建一个实时更新新数据条目/删除而不刷新的表?