js 怎么将数组重组成新数组

原数据结构:

var res =[  0:{id: "1", letter: "D", name_cn: "大学名字"}  1:{id: "2", letter: "A", name_cn: "大学名字"}  2:{id: "3", letter: "C", name_cn: "大学名字"}  3:{id: "3", letter: "D", name_cn: "大学名字"}
]

要实现的数据结构:

            schoolList: [
                {                    letter: 'A',                    data: [
                        {name_cn:'大学名字'},
                        {name_cn:'大学名字'}
                    ]
                },
                {                    letter: 'B',                    data: [
                        {name_cn:'大学名字'}
                        {name_cn:'大学名字'}

                    ]
                },
                {                    letter: 'C',                    data: [
                        {name_cn:'大学名字'}
                        {name_cn:'大学名字'}

                    ]
                }
            ]

怎么将res这个数组里面的letter,按照首字母分类。将首字母为一样的全部重新组成新的数组,然后放在schoolList这个数组里面。


一只名叫tom的猫
浏览 1158回答 2
2回答

慕运维8079593

暂时想到这种稍微复杂点的方法var&nbsp;res&nbsp;=[ &nbsp;&nbsp;{id:&nbsp;"1",&nbsp;letter:&nbsp;"D",&nbsp;name_cn:&nbsp;"大学名字5"}, &nbsp;&nbsp;{id:&nbsp;"2",&nbsp;letter:&nbsp;"A",&nbsp;name_cn:&nbsp;"大学名字4"}, &nbsp;&nbsp;{id:&nbsp;"4",&nbsp;letter:&nbsp;"C",&nbsp;name_cn:&nbsp;"大学名字3"}, &nbsp;&nbsp;{id:&nbsp;"5",&nbsp;letter:&nbsp;"D",&nbsp;name_cn:&nbsp;"大学名字2"}, &nbsp;&nbsp;{id:&nbsp;"6",&nbsp;letter:&nbsp;"C",&nbsp;name_cn:&nbsp;"大学名字1"}, &nbsp;&nbsp;{id:&nbsp;"7",&nbsp;letter:&nbsp;"D",&nbsp;name_cn:&nbsp;"大学名字0"} ] var&nbsp;op&nbsp;=&nbsp;[]; var&nbsp;middle&nbsp;=&nbsp;'';for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;res.length;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;value&nbsp;=&nbsp;res[i]['letter'];&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(middle.includes(value&nbsp;))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;index&nbsp;=&nbsp;middle.indexOf(value); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;op[index]['data'].push(res[i]['name_cn']); &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;middle+=value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;a&nbsp;=&nbsp;{&nbsp;letter:&nbsp;value,&nbsp;data:&nbsp;[res[i]['name_cn']]&nbsp;}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;op.push(a); &nbsp;&nbsp;&nbsp;&nbsp;} }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript