如何使用map函数检查json中的属性是否缺失并返回0

时间:2016-03-10 12:42:40

标签: underscore.js

我希望按名称分组并汇总core_mt ***值字段(如果存在)或将0添加到该字段的总和

var result = [{ "core_year": "2015", "core_mtdaugvalue": "640", "core_mtdaugqty_decimal": "40", "name": "PRECEPT EC150 1X20L DRM AU", "defaultuomid": { "entityName": "uom", "id": "a566917b-c659-e411-8b5b-0050568902b7", "isNew": false, "primaryName": "L" } }, { "core_year": "2015", "core_mtdaugvalue": "3780", "core_mtdsepvalue": "1260", "core_mtdaugqty_decimal": "120", "core_mtdsepqty_decimal": "40", "name": "VELOCITY EC347,2 1X20L DRM AU", "defaultuomid": { "entityName": "uom", "id": "a566917b-c659-e411-8b5b-0050568902b7", "isNew": false, "primaryName": "L" } }];

var finalResult = _.chain(result)
                        .groupBy("name")
                        .map(function (value, key) {
                            return {
                                brandname: key,
                                Value: _.map(function (value) {

                                    var sum = 0;

                                    if (value[0].core_mtdjanvalue == undefined)
                                        sum = sum + 0;
                                    else
                                        sum = sum + value[0].core_mtdjanvalue;

                                    return { Value: sum };
                                })
                            }
                        })
                       .value();

我尝试了上面的代码,但它返回null,如下所示

[{"brandname":"PRECEPT EC150 1X20L DRM AU","Value":[null]},{"brandname":"VELOCITY EC347,2 1X20L DRM AU","Value":[null]}]

谁能告诉我哪里出错了。提前谢谢。

0 个答案:

没有答案