首页 > 解决方案 > 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
  }
}

标签: jqueryloopsobjectforeach

解决方案


推荐阅读