简体   繁体   English

如何使用Underscore.js映射精简嵌套数组

[英]How to Map Reduce nested arrays with Underscore.js

Given: 鉴于:

appliedDoses = {
  "_id": "MAIN",
  "scheme": {
    "_id": "MAIN_SCHEME",
    "name": "ESQUEMA CLASICO",
    "vaccines": [
      {
      "_id": "BCG",
      "__v": 0,
      "doses": [
        {
        "_id": "BCG_UNICA",
        "frequencies": [
          {
          "_id": "BCG_UNICA_RECIEN_NACIDO",
          "group_type": {
            "_id": "RECIEN_NACIDO",
            "name": "RECIEN NACIDO"
          },
          "__v": 0,
          "status": true,
          "number_applied": 10
        }, ...

What I want is to filter by group_type.id == "RECIEN_NACIDO" and doses[]._id == "BCG_UNICA" then get a total sumatory of frequencies[].number_applied 我想要的是通过group_type.id == "RECIEN_NACIDO"doses[]._id == "BCG_UNICA"进行过滤,然后获得frequencies[].number_applied的总和frequencies[].number_applied

I tried: 我试过了:

async.each(appliedDose, function(scheme){
  async.each(scheme.scheme.vaccines, function(vaccine){
    async.each(vaccine.doses, function(dose){ 
      if(dose._id == getDose) {
        async.each(dose.frequencies, function(frequencie){
          if(frequencie.group_type._id == getGroup) {
            applied += frequencie.number_applied;
          }
        });
      }
    });
  });
});

But my code isn't quite efficiently and I was wondering if MapReduce can be used to improve it. 但是我的代码效率不高,我想知道是否可以使用MapReduce进行改进。 Can somebody give me a hint? 有人可以给我提示吗? Help is much appreciated! 非常感谢帮助!

I'm a little confused by the object you're dealing with so I'll try to deal in abstraction. 我对您要处理的对象有些困惑,因此我将尝试抽象处理。 What you're probably looking to do here is easier and faster if you break it down. 如果您将其分解,那么您可能想要在这里做的事情变得更容易,更快。

get the collection that results from filtering by: group_type._id == "RECIEN_NACIDO" && doses._id 通过以下方式获取过滤所得的集合: group_type._id == "RECIEN_NACIDO" && doses._id

get the array of number_applied's by plucking them out with _.pluck 通过使用_.pluck拔出number_applied的数组

reduce that with sum: _.reduce(numAppliedArray, function(sum, x) { return sum + x}, 0); 用sum减少它: _.reduce(numAppliedArray, function(sum, x) { return sum + x}, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM