简体   繁体   English

遍历对象的麻烦

[英]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: 我正在尝试做的是获取状态为“ 1”的所有货币的所有金额,并将其放入应如下所示的对象中:

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. 我继续得到{"CAD":{"1":"250"},"USD":{"1":"180"}}这是到目前为止的代码。

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. 顺便说一句,这与jQuery无关。

Note that Object.keys is ES5 so may need a polyfill for older browsers, see MDN:Object.keys for code. 请注意, Object.keys是ES5,因此对于较旧的浏览器可能需要使用polyfill,有关代码,请参见MDN:Object.keys

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() 无论如何,对不起您的深聊,请尝试使用.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 演示版

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

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