首页 > 解决方案 > 使用Javascript的Json中特定属性的总和

问题描述

我正在使用 Asp.net MVC ,并且从我的 ActionResult 我使用 TempData 返回数据。像这样

 TempData["chartmodel"] = new
        {
            Labels = res.Select(x => x.ServiceName).ToList(),                                  //changes hotel name to service
            BadData = res.Select(x => x.Development).ToList(),
            ExcellentData = res.Select(x => x.Excellent).ToList(),
            GoodData = res.Select(x => x.Average).ToList(),
            VeryGoodData = res.Select(x => x.Good).ToList(),
            PoorData = res.Select(x => x.unsatisfactory).ToList(),
        };
        return View(res);

在我的视图中,我将其编码为 json

 var chartModel = @Html.Raw(Json.Encode(TempData["chartmodel"]));

现在我只想总结优秀的财产。假设我有数据

chartModel.ExcellentData =2,3,5

我想将它总结为一个变量10

标签: javascriptjsonasp.net-mvcsum

解决方案


使用reduce

var sumVariable = chartModel.ExcellentData.reduce(function(e, a) { return e + a; }, 0)

推荐阅读