扁平数据结构化

var sourceData = [{
        date: '2018-03-23',
        totalMoney: '500',
        goodsCount: '12'
    }, {
        date: '2018-03-22',
        totalMoney: '500',
        goodsCount: '23'
    }, {
        date: '2018-02-20',
        totalMoney: '300',
        goodsCount: '11'
    }, {
        date: '2018-02-18',
        totalMoney: '300',
        goodsCount: '12'
    }]


    // [{
    //         date: '2018-03',
    //         totalMoney: '500',
    //         list: [{ goodsCount: '12'}, { goodsCount: '23'}]
    //     }
    // ]

    function flat2StructData(sourceData) {
        // 计算出结果数组的元素个数
        var temArr = new Set()
        sourceData.forEach(function(data, index) {
            temArr.add(data.date.substring(0, 7))
        })
        debugger
        var result = [],
            tmpA = [...temArr]

        tmpA.forEach(function(item, itemIndex) {
            result[itemIndex] = {
                date: item,
                totalMoney: '',
                list: []
            }
            sourceData.forEach(function(data, index) {
                // 相同年月的数据整合到一起
                if (!result[itemIndex].date || result[itemIndex].date == data.date.substring(0, 7)) {
                    result[itemIndex].totalMoney = data.totalMoney
                    result[itemIndex].list[index] = {
                        goodsCount: data.goodsCount
                    }
                }
            })
        })

        console.log(result)
        return result
    }
    flat2StructData(sourceData)

猜你喜欢

转载自www.cnblogs.com/wenhandi/p/9391023.html