zoukankan      html  css  js  c++  java
  • reduce过滤数组

    原始数据

    const data = [{
            id: 1,
            spec: '规格1',
            rules: [{
                    rank: 10,
                    breaks: 100
                },
                {
                    rank: 50,
                    breaks: 10
                },
                {
                    rank: 100,
                    breaks: 5
                }
            ]
        },
        {
            id: 2,
            spec: '规格2',
            rules: [{
                    rank: 10,
                    breaks: 200
                },
                {
                    rank: 50,
                    breaks: 20
                },
                {
                    rank: 100,
                    breaks: 25
                }
            ]
        }
    ];

    使用 forEach 遍历

    function skuFormat(data) {
        let RankList = [];
        data.forEach(item => {
            item.rules.forEach(ite => {
                if (RankList.indexOf(ite.rank) === -1) RankList.push(ite.rank);
            })
        })
        let newData = [];
        RankList.forEach(item => {
            newData.push({
                rank: item,
                skus:[]
            })
        })
        newData.forEach(item=>{
            data.forEach(ite=>{
                let Remark={
                    id:ite.id,
                    spec:ite.spec,
                    breaks:0
                }
                try {
                    ite.rules.forEach(it=>{
                    if(item.rank===it.rank){
                        Remark.breaks=it.breaks;
                        item.skus.push(Remark);
                        throw(new Error('find item'));
                    }
                })
                } catch (error) {
                }
            })
        })
        return newData;
    }
    let newData= skuFormat(data);
    console.log(newData)

    使用 reduce 处理

    let newData=data.reduce((pre, cur) => {
        console.log(cur,pre)
        const list = cur.rules.map(item => ({
            rank: item.rank,
            skus: [{
                id: cur.id,
                spec: cur.spec,
                breaks: item.breaks
            }]
        }))
        if (!pre.length) {
            return list;
        }
        return pre.map((item, key) => {
            return {
                ...item,
                skus: [...item.skus, ...list[key].skus]
            }
        })
    }, []);
    console.log(newData)
  • 相关阅读:
    java多线程小节, 总结的不错
    奇瑞风云, 你还在路上么
    android NDK 环境建立
    外企下岗白领正成为“新4050”
    搭积木
    祝MORIENTES在LIVERPOOL有所成就
    简单生活
    为什么要更新
    归去来
    随记一笔
  • 原文地址:https://www.cnblogs.com/gitByLegend/p/11739044.html
Copyright © 2011-2022 走看看