JS數(shù)組按指定字段轉map-list結構(示例詳解)
更新時間:2023年11月07日 09:24:20 作者:天葬
在開發(fā)過程中經常會出現(xiàn)接口返回整個數(shù)組,我們需要將數(shù)組進行二次處理,這篇文章主要介紹了js?數(shù)組按指定字段轉map-list結構,需要的朋友可以參考下
js 數(shù)組按指定字段轉map-list結構
背景介紹
在開發(fā)過程中經常會出現(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} ];
轉換方法
/** * @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ù)添加到相應 '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 } ] }
到此這篇關于js 數(shù)組按指定字段轉map-list結構的文章就介紹到這了,更多相關js數(shù)組轉map-list結構內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript中使用replace結合正則實現(xiàn)replaceAll的效果
JavaScript?中使用?replace?達到?replaceAll的效果,其實就用利用的正則的全局替換。2010-06-06JS中使用sort結合localeCompare實現(xiàn)中文排序實例
這篇文章主要介紹了JS中使用sort結合localeCompare實現(xiàn)中文排序實例,重點介紹localeCompare函數(shù),需要的朋友可以參考下2014-07-07chart.js實現(xiàn)動態(tài)網頁顯示拆線圖的效果
本文主要介紹了chart.js實現(xiàn)動態(tài)網頁顯示拆線圖的效果,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11詳解微信小程序-canvas繪制文字實現(xiàn)自動換行
這篇文章主要介紹了微信小程序canvas繪制文字實現(xiàn)自動換行,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04詳解JavaScript對數(shù)組操作(添加/刪除/截取/排序/倒序)
這篇文章主要介紹了JavaScript對數(shù)組操作,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04