简体   繁体   中英

Trouble iterating through an object

I have an object that looks like this:

salesDetails:{ "1":{
  "date":"06/22/2014",
  "amount":"45",
  "currency":"CAD",
  "productID":"23",
  "status":1},
"2":{
  "date":"06/22/2014",
  "amount":"120",
  "currency":"USD",
  "productID":"23",
  "status":1},
"3":{
  "date":"06/23/2014",
  "amount":"100",
  "currency":"USD",
  "productID":"21",
  "status":2},
"4":{
  "date":"06/23/2014",
  "amount":"250",
  "currency":"CAD",
  "productID":"25",
  "status":1},
"5":{
  "date":"06/23/2014",
  "amount":"180",
  "currency":"USD",
  "productID":"24",
  "status":1}
}

What i am trying to do is to get all the amount per currency of all that has status of "1" and put it in an object that should look like this:

perCurrency: {
 "CAD":{
  "0":"45", 
  "1":"250"},

 "USD":{
  "0":"120",
  "1":"180"}
}

I was able to put all the currency in an object but I'm having trouble with the amount, the last amount from the object overlaps the previous one. I keep on getting {"CAD":{"1":"250"},"USD":{"1":"180"}} Here's my code so far.

function countPerCurrency(){
  var currencyArray = new Array();
  var perCurrency = {}; 

  var totalSales = Object.size(salesDetails);

  for(var i=1; i <= totalSales; i++){
    var currency = salesDetails[i]["currency"];
    var amount = salesDetails[i]["amount"];
    var status = salesDetails[i]["status"];

    var totalCurrency = Object.size(currencyAmount[currency]);
    var currencyCtr = {};

    if(status == 1){
      if(!inArray(currency, currencyArray)){
        currencyArray.push(currency);
        currencyCtr[totalCurrency] = amount;
        perCurrency[currency] = currencyCtr;
      } else {
        var currencyAdd = {};
        currencyAdd[totalCurrency] = amount;
        perCurrency[currency] = currencyAdd;
      }
    }
  }         
}

I know it might seem easy, but I'm lost here.. TIA! :)

The previously accepted answer uses an array of values, whereas you asked for an object. Here's an object version:

var perCurrency = {};
var currencyCount = {};

Object.keys(salesDetails).forEach(function(key) {
  var obj = salesDetails[key];
  var currency;

  if (obj.status == 1) {
    currency = obj.currency;

    // If this is first for this currency, add it to objects
    if (!currencyCount[currency]) {
      currencyCount[currency] = 0;
      perCurrency[currency] = {};
    }

    // Add currency values
    perCurrency[currency][currencyCount[currency]++] = obj.amount;
  }
}); 

BTW, this has nothing to do with jQuery.

Note that Object.keys is ES5 so may need a polyfill for older browsers, see MDN:Object.keys for code.

try something like this

    function countPerCurrency(){
          var perCurrency = {};
          var totalSales = Object.size(salesDetails);
          for(var i=1; i <= totalSales; i++){
            var currency = salesDetails[i]["currency"];
            var amount = salesDetails[i]["amount"];
            var status = salesDetails[i]["status"];

            if(status == '1'){
                if(perCurrency.hasOwnProperty(currency)){
                    // if currency already present than get currency array.
                    var currency_arr = perCurrency[currency];
                    // add new value to existing currency array.
                    currency_arr.push(amount);

                }else{
                    // if currency not present than create currency array and add first value;
                    var currency_arr = [];
                    currency_arr.push(amount);
                    // add newly created currency array to perCurrency object
                    perCurrency[currency] = currency_arr;

                }
            }
          }
          console.log(perCurrency);
    }

output

    perCurrency: {
        "CAD":["45","250"],
        "USD":["120","180"],
    }

I have created currency array instead of key value pair

Change your code like this, i have simplified your things,

function countPerCurrency() {

   var perCurrency    = {}; 
       var currencyArray  = [];

   for(i in salesDetails)
   {
         if(!perCurrency.hasOwnProperty(salesDetails[i].currency) && salesDetails[i].status === "1")
               perCurrency[salesDetails[i].currency]     = [];


         if(salesDetails[i].status === "1")
         {
              currencyArray      = perCurrency[salesDetails[i].currency];
              currencyArray.push(salesDetails[i].amount);
              perCurrency[salesDetails[i].currency]     =    currencyArray;
         }   

   }     
}

sorry for the late conversation anyway try like this use .each()

var CAD = new Array();
var USD = new Array();

$.each(salesDetails, function (i, value) {

    if (value.status == 1) {

        if (value.currency == "CAD") {
            CAD.push(value.amount);

        } else if (value.currency == "USD") {
            USD.push(value.amount);

        }

    }

});
var perCurrency = {
    "CAD": CAD,
    "USD": USD
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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