javascript - 如何求key的值之和?

标签 javascript jquery collections underscore.js

我有一个这样的集合:

{
    "2.2": { 
        "BALL":{"white":9,"black":11,"red":4},
        "BAG":{"white":2,"black":11,"red":1},
        "COVER":{"white":3,"black":8,"red":1}
    },
    "2.3": {
        "BALL":{"white":1,"black":0,"red":7},
        "BAG":{"white":3,"black":0,"red":0},
        "COVER":{"white":9,"black":2,"red":28}
    }
}

我想计算“2.2”和“2.3”的颜色总和(白色、黑色、红色)。

输出 所需的输出应该是这样的:

{
    "2.2": {"white": 14, "black": 30, "red": 6},
    "2.3": {"white": 13, "black": 2, "red": 35}
}

我尝试使用 underscore .map 函数,但我无法正确理解它。任何人都可以帮忙。 ? PS:需要一个仅使用 underscore.js 的解决方案。

最佳答案

这是 underscore.js 解决方案。

_.mapObject(collections, function(collection) {
  return _.reduce(collection, function(memo, col) {
    // credit: Bergi on http://stackoverflow.com/a/17350790/1465828
    // the following line reads:
    // for (var p in col) => loop all properties in col
    // memo[p] = ... => assign memo[p] as ...
    // (p in memo ? memo[p] : 0) => IF property p exists in memo, then memo[p], otherwise 0
    // + col[p] => add col's p
    for (var p in col) { memo[p] = (p in memo ? memo[p] : 0) + col[p]; }
    return memo;
  }, {});
});

关于javascript - 如何求key的值之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30341930/

相关文章:

javascript - onClick 将 'POST' 数据发送到 php 文件并获取结果

Java:通过引用集合克隆任意集合

javascript - 重新格式化 JS 代码片段的最佳方法

javascript - 不推荐访问存储桶虚拟托管样式的 URL? (AWS S3)

javascript - 试图减少图像延迟。预加载或

jquery - 在显示 div 时它总是显示在页面顶部

jQuery 自动完成将 null 参数传递给 ASP.NET MVC 2 中的 Controller

ajax - 防止在 AJAX 请求上发送 Cookie

java - Collections.unmodifiableList 是否存在性能风险?

java - LinkedHashSet 作为 API 公共(public)方法的返回类型