欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論