1

私はchargeamountunitLevelと呼ばれる配列を持つjsonを持っています。chargeAmountUnit.The 入力 json でグループ化して、chargeAmount を合計したい:

 "chargeamountunitLevel": [
        {
            "chargeAmount": 4,
            "chargeAmountUnit": "per hour",
            "currencyCode": "USD"
        },
        {
            "chargeAmount": 50,
            "chargeAmountUnit": "per hour",
            "currencyCode": "USD"
        },
        {
             "chargeAmount": 25,
             "chargeAmountUnit": "per month",
             "currencyCode": "USD"
        },
        {
             "chargeAmount": 25,
             "chargeAmountUnit": "per month",
             "currencyCode": "USD"
        }

    ]

結果は次のようになります。

    "chargeamountunitLevel": [
        {
            "chargeAmount": 54,
            "chargeAmountUnit": "per hour",
            "currencyCode": "USD"
        },
        {
             "chargeAmount": 50,
             "chargeAmountUnit": "per month",
             "currencyCode": "USD"
        }

        ]

助言がありますか?

4

2 に答える 2

0

underscore.js を使用できます

コードは次のとおりです。

var _ = require('underscore');    // use `npm install underscore`
var util = require('util');       // nodejs default modules

var data = {
  "chargeamountunitLevel": [{
    "chargeAmount": 4,
    "chargeAmountUnit": "per hour",
    "currencyCode": "USD"
  }
  , {
    "chargeAmount": 50,
    "chargeAmountUnit": "per hour",
    "currencyCode": "USD"
  }
  , {
    "chargeAmount": 25,
    "chargeAmountUnit": "per month",
    "currencyCode": "USD"
  }
  , {
    "chargeAmount": 10,
    "chargeAmountUnit": "per month",
    "currencyCode": "USD"
  }
  , {
    "chargeAmount": 1,
    "chargeAmountUnit": "per month",
    "currencyCode": "RMB"
  }
  , {
    "chargeAmount": 25,
    "chargeAmountUnit": "per month",
    "currencyCode": "HKD"
  }]
};

// This should give you an array of objects that
// are grouped by chargeAmountUnit.
var tmp = _.groupBy(data["chargeamountunitLevel"], function(d){ 
  return d["chargeAmountUnit"]; 
});
// Show the temporary result :o)
console.log(tmp);

// Now group the result with currency code
var tmp2 = {};
_.each(tmp, function(t, unit){
  tmp2[unit] = _.groupBy(t, function(d){
    return d["currencyCode"];
  });
});

// show the temp result again
console.log("tmp2: \n" +  util.inspect(tmp2, false, null, true));   // util.inspect() is different in node v0.10.x

var finalResult = [];
_.each(tmp2, function(t, unit){
  _.each(t, function(items, currency){
    var total = 0;
    _.each(items, function(item){
      total += item["chargeAmount"];     // should also * currencyCode?
    });
    finalResult.push({
      "chargeAmountUnit" : unit
      , "chargeAmount" : total
      , "currencyCode" : currency    // Update it yourself :o)
    });
  });
});

console.log(finalResult);
于 2013-08-18T13:06:04.247 に答える