用underscore.js求和

时间:2019-05-14 08:27:34

标签: underscore.js

我有如下的JSON数据。

{  
   "market":[  
      {  
         "aciklama":"Migros",
         "kategori":"market",
         "odeme_tipi":"kredi_karti",
         "tarih":{  
            "seconds":1557673429,
            "nanoseconds":599000000
         },
         "tutar":"10",
         "user_email":"xyz@gmail.com",
         "user_uid":"6xx"
      },
      {  
         "aciklama":"Pidesi",
         "kategori":"market",
         "odeme_tipi":"nakit",
         "tarih":{  
            "seconds":1557173938,
            "nanoseconds":955000000
         },
         "tutar":"5",
         "user_email":"xyz@gmail.com",
         "user_uid":"6xx"
      }
   ],
   "diger":[  
      {  
         "aciklama":"Tatlı",
         "kategori":"diger",
         "odeme_tipi":"nakit",
         "tarih":{  
            "seconds":1557591963,
            "nanoseconds":180000000
         },
         "tutar":"20",
         "user_email":"xyz@gmail.com",
         "user_uid":"6xx"
      }
   ]
}

我想通过market属性获取digertutar的子节点的总和,并希望使用underscore.js提取此结果:

market: 15 
diger: 20

我尝试了undersore.js的reduce函数,但不能。提取子节点并对其进行处理的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我不确定为什么要为此使用一个库...纯JS:

let res = {};
for(let category in myObj) {
     res[category] = 0;

     for(let sub of myObj[category]) {
        res[category] += parseInt(sub.tutar, 10);             
     }
}
return res;

或者,如果您真的想使用库,可以使用具有sum函数https://lodash.com/docs/4.17.11#sumBy的lodash:

let res = {};
for(let category in myObj) {
     res[category] = _.sumBy(myObj[category], o => parseInt(o.tutar, 10));
}
return res;

或者使用下划线js reduce:

let res = {};
for(let category in myObj) {
     res[category] = _.reduce(myObj[category], (memo, sub) => { return memo + parseInt(sub.tutar, 10); }, 0);
}
return res;

答案 1 :(得分:1)

您可以使用纯JS OFC来做到这一点,但这是一种使用[reduce的{​​{3}}方法。(underscore.js

const input = {
  "market": [{
    "aciklama": "Migros",
    "kategori": "market",
    "odeme_tipi": "kredi_karti",
    "tarih": {
      "seconds": 1557673429,
      "nanoseconds": 599000000
    },
    "tutar": "10",
    "user_email": "xyz@gmail.com",
    "user_uid": "6xx"
  }, {
    "aciklama": "Pidesi",
    "kategori": "market",
    "odeme_tipi": "nakit",
    "tarih": {
      "seconds": 1557173938,
      "nanoseconds": 955000000
    },
    "tutar": "5",
    "user_email": "xyz@gmail.com",
    "user_uid": "6xx"
  }],
  "diger": [{
    "aciklama": "Tatlı",
    "kategori": "diger",
    "odeme_tipi": "nakit",
    "tarih": {
      "seconds": 1557591963,
      "nanoseconds": 180000000
    },
    "tutar": "20",
    "user_email": "xyz@gmail.com",
    "user_uid": "6xx"
  }]
};

var output = _.reduce(_.pairs(input), (memo, kv) => {
  const key = kv[0];
  memo[key] = _.reduce(kv[1],
    (memo1, o) => memo1 + parseInt(o.tutar),
    0);
  return memo;
}, {});

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>