对两个对象执行基本合并的Javascript方法[重复]

我有两个看起来像的对象:

{
    "data" : [ 
        {
            "name" : "toyota",
            "type" : "cars",
            "totals" : {
                "invalid" : 4,
                "valid" : 14,
                "percentage" : 77.78,
                "total" : 18
            }
        }
    ],
    "report_id": "123wa31a22aba05"
}

我想使用以下规则将这两个对象合并为一个对象:

Every two cars that have the same name and type in the data should be merged. This means that totals will be:

"totals": {
    "invalid": "invalidA" + "invalidB"
    "valid": "validA" + "validB"
    "percentage" : calculatePercentage("invalid","valid")
    "total": "invalid" + "valid"
}

如果只有具有某些名称和类型的子对象,它将直接将其推送到合并报表中。

What I thought: Copy object one to result object. Then iterate over the second object and insert the elements into the result object (merge if needed). I would use the for loop as I'm used from Java, but it doesn't feel a good js code. What is the proper way to merge those two object in JS?

简化示例:

对象1:

{
    "data" : [ 
        {
            "name" : "toyota",
            "type" : "cars",
            "totals" : {
                "invalid" : 4,
                "valid" : 14,
                "percentage" : 77.78,
                "total" : 18
            }
        }
    ],
    "report_id": "123wa31a22aba05"
}

对象2:

{
    "data" : [ 
        {
            "name" : "toyota",
            "type" : "cars",
            "totals" : {
                "invalid" : 2,
                "valid" : 5,
                "percentage" : 71.42,
                "total" : 7
            }
        }
    ],
    "report_id": "123wa31a22aba06"
}

结果:

{
    "data" : [ 
        {
            "name" : "toyota",
            "type" : "cars",
            "totals" : {
                "invalid" : 6,
                "valid" : 19,
                "percentage" : 76.0,
                "total" : 25
            }
        }
    ]
}
评论