JS數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)(示例詳解)
js 數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)
背景介紹
在開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)出現(xiàn)接口返回整個(gè)數(shù)組,我們需要將數(shù)組進(jìn)行二次處理,如下格式按照不同功能模塊(type)進(jìn)行數(shù)據(jù)拆分
原始數(shù)據(jù)
const list = [ {"type":"red","id":1,"name":"a","count":1}, {"type":"red","id":2,"name":"b","color":2}, {"type":"green","id":3,"name":"c","color":3}, {"type":"green","id":4,"name":"d","color":4}, {"type":"blue","id":5,"name":"e","color":4}, {"type":"blue","id":6,"name":"f","color":4} ];
轉(zhuǎn)換方法
/** * @param {Object} listData 原始數(shù)據(jù) * @param {Object} field 字段 key */ const arrayToMap = (listData,field)=>{ const arrayMap = {}; listData.forEach(item => { const item_type = item[field]; if (!arrayMap[item_type]) { arrayMap[item_type] = []; } // 將數(shù)據(jù)添加到相應(yīng) 'type' 的數(shù)組中 arrayMap[item_type].push(item); }); return arrayMap; }
測(cè)試驗(yàn)證
console.log(arrayToMap(list,'type')) { "red": [ { "type": "red", "id": 1, "name": "a", "count": 1 }, { "type": "red", "id": 2, "name": "b", "color": 2 } ], "green": [ { "type": "green", "id": 3, "name": "c", "color": 3 }, { "type": "green", "id": 4, "name": "d", "color": 4 } ], "blue": [ { "type": "blue", "id": 5, "name": "e", "color": 4 }, { "type": "blue", "id": 6, "name": "f", "color": 4 } ] }
到此這篇關(guān)于js 數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)的文章就介紹到這了,更多相關(guān)js數(shù)組轉(zhuǎn)map-list結(jié)構(gòu)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript中使用replace結(jié)合正則實(shí)現(xiàn)replaceAll的效果
JavaScript?中使用?replace?達(dá)到?replaceAll的效果,其實(shí)就用利用的正則的全局替換。2010-06-06Javascript刪除指定元素節(jié)點(diǎn)的方法
這篇文章主要介紹了使用Javascript刪除指定元素節(jié)點(diǎn)的方法,通俗易懂,需要的朋友可以參考下。2016-06-06

JavaScript練習(xí)小項(xiàng)目之修改div塊的顏色

chart.js實(shí)現(xiàn)動(dòng)態(tài)網(wǎng)頁(yè)顯示拆線圖的效果

詳解微信小程序-canvas繪制文字實(shí)現(xiàn)自動(dòng)換行

詳解JavaScript對(duì)數(shù)組操作(添加/刪除/截取/排序/倒序)