JS數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)(示例詳解)
js 數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)
背景介紹
在開發(fā)過程中經(jīng)常會出現(xiàn)接口返回整個數(shù)組,我們需要將數(shù)組進行二次處理,如下格式按照不同功能模塊(type)進行數(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; }
測試驗證
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript中使用replace結(jié)合正則實現(xiàn)replaceAll的效果
JavaScript?中使用?replace?達(dá)到?replaceAll的效果,其實就用利用的正則的全局替換。2010-06-06

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

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

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