最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)(示例詳解)

 更新時(shí)間:2023年11月07日 09:24:20   作者:天葬  
在開發(fā)過程中經(jīng)常會(huì)出現(xiàn)接口返回整個(gè)數(shù)組,我們需要將數(shù)組進(jìn)行二次處理,這篇文章主要介紹了js?數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu),需要的朋友可以參考下

js 數(shù)組按指定字段轉(zhuǎn)map-list結(jié)構(gòu)

背景介紹

在開發(fā)過程中經(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)文章

最新評(píng)論

洞口县| 阳泉市| 新郑市| 南皮县| 庆云县| 阿拉尔市| 湖州市| 永平县| 海原县| 伊金霍洛旗| 百色市| 景东| 历史| 米林县| 嵩明县| 贵南县| 彝良县| 贵定县| 宜宾县| 长泰县| 庆安县| 卢龙县| 铜川市| 万州区| 康马县| 三台县| 中阳县| 西畴县| 禹城市| 三河市| 龙川县| 梨树县| 垫江县| 静乐县| 萨迦县| 禹城市| 尼玛县| 九江市| 甘谷县| 镇平县| 沙河市|