美文网首页
js处理数据,去重+组成二维数组

js处理数据,去重+组成二维数组

作者: 甘道夫老矣 | 来源:发表于2024-03-11 10:30 被阅读0次
 // 加载表格数据
    initTableData(): void {



        const data = [
            {
                "indicatrixId": 1,
                "indicatrixName": "水田",
                "items": [
                    {
                        "key": "大湾镇",
                        "value": 80
                    },
                    {
                        "key": "大湾2镇",
                        "value": 20
                    }
                ]
            },
            {
                "indicatrixId": 2,
                "indicatrixName": "旱地",
                "items": [
                    {
                        "key": "香港镇",
                        "value": 80
                    },
                    {
                        "key": "大湾2镇",
                        "value": 10
                    }
                ]
            }
        ]

        const result: any = {}
        // 这一步是找到对应的镇
        data .forEach((item: any) => {
            const { items } = item;
            items.forEach((elm: any) => {
                if (!result[elm.key]) {
                    result[elm.key] = []
                }
            })

        })
        console.log(result)

        // 循环数值,然后赋值key:[80,10,20,....],
        data .forEach((item:any)=>{
            const { items } = item;
            // 循环obj的key
            Object.keys(result).forEach(key => {
                const currentItem = items.find((elm:any) => elm.key === key)
                result[key].push(currentItem ? currentItem.value : 0)
            })
        })

        // 把对象组成二维数值
        const returnValue: any = []
        Object.keys(result).forEach(key => {
            returnValue.push([
                key,
                ...result[key]
            ])
        })
        console.log(returnValue)
    }
514fb98334968ccf7b21624f7c1b063.png

相关文章

网友评论

      本文标题:js处理数据,去重+组成二维数组

      本文链接:https://www.haomeiwen.com/subject/bytoodtx.html