js两个数组根据对象中某一相同属性,计算合并其他项,无相同不计算

image.png
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var arr1 = [{
                YearMonth: "2021-08",
                PassNum: 20,
                NotPassNum: 5,
                AllNum: 25
            },
            // {
            //     YearMonth: "2021-09",
            //     PassNum: 21,
            //     NotPassNum: 0,
            //     AllNum: 21
            // },
            {
                YearMonth: "2021-10",
                PassNum: 16,
                NotPassNum: 1,
                AllNum: 17
            }, {
                YearMonth: "2021-11",
                PassNum: 10,
                NotPassNum: 0,
                AllNum: 11
            }
        ]
        var arr2 = [{
            YearMonth: "2021-08",
            PassNum: 30,
            NotPassNum: 5,
            AllNum: 35
        }, {
            YearMonth: "2021-09",
            PassNum: 41,
            NotPassNum: 0,
            AllNum: 41
        }, {
            YearMonth: "2021-10",
            PassNum: 45,
            NotPassNum: 1,
            AllNum: 46
        }, {
            YearMonth: "2021-11",
            PassNum: 80,
            NotPassNum: 1,
            AllNum: 81
        }]
        var newobj = []

        var arry = arr1.concat(arr2);


        let newfood = [];
        var temp = {};
        for (var i in arry) {
            var key = arry[i].YearMonth;
            if (temp[key]) {
                temp[key].YearMonth = temp[key].YearMonth;
                temp[key].PassNum = temp[key].PassNum + arry[i].PassNum;
                temp[key].NotPassNum = temp[key].NotPassNum + arry[i].NotPassNum;
                temp[key].AllNum = temp[key].AllNum + arry[i].AllNum;

            } else {
                temp[key] = {};
                temp[key].YearMonth = arry[i].YearMonth;
                temp[key].PassNum = arry[i].PassNum;
                temp[key].NotPassNum = arry[i].NotPassNum;
                temp[key].AllNum = arry[i].AllNum;

            }
            // temp[key].ItemType= arry[i].ItemType; 
        }
        for (var k in temp) {
            newfood.push(temp[k])
        }



        function dateDate(property, bol) {
            return function(a, b) {
                var value1 = a[property];
                var value2 = b[property];
                if (bol) {
                    return Date.parse(value1) - Date.parse(value2);
                } else {
                    return Date.parse(value2) - Date.parse(value1);
                }
            };
        }

        var ddd = newfood.sort(dateDate("YearMonth", true))

    </script>
</body>

</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容