【发布时间】:2026-01-19 09:55:01
【问题描述】:
我有一个数据源以表格形式抽出数据:
arr = [{
"type": "engineering",
"name": "Physics",
"name_id": 6,
"strength": [21,33,12],
"batch": 191
}, {
"type": "engineering",
"name": "Computer and Mathematics",
"name_id": 8,
"strength": [1,3],
"batch": 192
}, {
"type": "engineering",
"name": "Computer and Mathematics",
"name_id": 8,
"strength": [1,33],
"batch": 193
}, {
"type": "engineering",
"name": "Physics",
"name_id": 6,
"strength": [2,33],
"batch": 194
}, {
"type": "mbbs",
"name": "Surgery",
"name_id": 16,
"strength": [21,3],
"batch": 195
}, {
"type": "mbbs",
"name": "Dental",
"name_id": 26,
"strength": [21,3],
"batch": 196
}, {
"type": "mbbs",
"name": "Dental",
"name_id": 26,
"strength": [21,33,43],
"batch": 197
}]
根据我的要求,我必须将数据推送到具有以下格式的数组:
[{
"engineering": {
"subject": [{
"name":{
"name": "Physics",
"name_id": 6
},
"class":{
"batch": [191,194],
"strength":[21,33,12,2,33]
}
},
{
"name":{
"name": "Computer and Mathematics",
"name_id": 8
},
"class":{
"batch": [192,193],
"strength":[1,3,1,33]
}
}],
},
"mbbs":{
"subject": [{
"name":{
"name": "Surgery",
"name_id": 16
},
"class":{
"batch": 195,
"strength":[21,3,195]
}
},
{
"name":{
"name": "Dental",
"name_id": 8
},
"class":{
"batch": [196,197],
"strength":[21,3,21,33,43]
}
}],
}
}]
我想按照上面给出的格式对数据进行分类。基本上它将创建两个类别,Engineering 和mbbs。
我将不胜感激对此的任何指导。我的解决方案有效,但如果有很多记录,我无法弄清楚为什么我的所有数据都没有被迭代。
我正在使用forEach 循环。
【问题讨论】:
-
你说的这个
forEach循环在哪里? -
您必须提供您尝试过的内容。老实说,我怀疑有人会从头开始为您编写此代码。
-
你想让任何人完成你的代码吗:)
标签: javascript jquery arrays json