jquery - Javascript推送对象并在foreach循环中计数
问题描述
我正在处理 jQuery 中的用户 .forEach 循环,我想创建一个用户组的对象数组以用于其他用途。而不是再次为所有用户提取数据以获取该功能
这是我下面的例子
var data = [
{
"user_id": '1',
"username": "test2",
"email": "test@test.com",
"access_type": "admin"
},
{
"user_id": '2',
"username": "test2",
"email": "test2@test2.com",
"access_type": "admin"
}, {
"user_id": '3',
"username": "test3",
"email": "test3@test3.com",
"access_type": "user"
}
];
var users_select = {};
data.forEach(function(i){
var type = i.access_type;
var setup = users_select;
var fullcount = setup.type.typecount;
if(fullcount !== undefined){
fullcount = fullcount + 1;
} else {
setup[type] = {'name':type,'typecount':0};
}
});
console.log(users_select);
//example of data for the for each loop
我收到错误“Uncaught TypeError: Cannot read property 'typecount' of undefined” if 语句应该足以设置对象
所需的输出应如下所示
{ admin: {
name: "admin",
typecount: 2
},
user: {
name: "admin",
typecount: 1
}
}
解决方案
推荐阅读
- c# - 复制和粘贴 xml 结构片段
- jmeter - 从 csv 读取数据并形成 JSON 数组,然后 POST -JMETER 4.0
- pie-chart - 如何在 apexcharts.js 上仅返回饼图中的值不会转换百分比
- bash - 在(bash)for循环中顺序运行程序
- node.js - 如何使用 sequelize 在 sqlite 文件的架构中的主键中写入非空值?
- android - 即使在 android arm64-v8a 上的 root 中,Execvp 也失败并显示 errno 13
- docker - 运行容器是什么意思?
- c# - 如何使用 c# 获取 sqlite 数据库中所有表的所有名称?
- c# - 如何以编程方式更新实体模型 (EF 5)
- c - 如何修复 stm32 上 sntp 客户端中的 MEMP_SYS_TIMEOUT