简体   繁体   中英

better way to push json into different array

i want to push my json into different array.

Before I use if function inside my for loop it works fine, but i like to know if there is a simpler method, since if i have a lot of array I will have lots of if function inside my loop.

part of my json

[{"FROM_CURRENCY":"TWD","TO_CURRENCY":"AUD","CONVERSION_RATE":".0359"}
,{"FROM_CURRENCY":"HKD","TO_CURRENCY":"AUD","CONVERSION_RATE":".1393"}
,{"FROM_CURRENCY":"USD","TO_CURRENCY":"CNY","CONVERSION_RATE":"6.2448"}
,{"FROM_CURRENCY":"TWD","TO_CURRENCY":"CNY","CONVERSION_RATE":".2073"}
,{"FROM_CURRENCY":"EUR","TO_CURRENCY":"JPY","CONVERSION_RATE":"139.2115"}
,{"FROM_CURRENCY":"CNY","TO_CURRENCY":"TWD","CONVERSION_RATE":"4.8229"},

right now what i have inside my loop

if(json[i].TO_CURRENCY == 'TWD'){
        arrayApp.TWD.push(json[i]);}

if(json[i].TO_CURRENCY == 'HKD'){
        arrayApp.HKD.push(json[i]);}

because i have many different currency i have to write a alot

here is what i'm thinking but doesn't seem to work

var setArrayCurr='';
for ( i in json ) { 
    setArrayCurr=json[i].TO_CURRENCY

    arrayApp.setArrayCurr.push(json[i]);

} //end of loop

try this:

var arrayApp = {};
for (i in json) {
    var arrayKey = json[i].TO_CURRENCY

    var array = arrayApp[arrayKey];
    //if first time for the key, then create an empty erray for the key.
    if (!array) {
        array = arrayApp[arrayKey] = [];
    }

    array.push(json[i]);

} //end of loop

end result would be multiple arrays grouped by the currency:

{
    "AWD": [ /* all jsons with currency 'AWD' */ ],
    "TWD": [ /* all jsons with currency 'TWD' */ ],
    "HKD": [ /* all jsons with currency 'HKD' */ ]
    ...
}

this is because you have set your setArrayCurr to string not array.

which means every time you declare setArrayCurr, it will change its context but not add nor categorize it.

var setArrayCurr = [];
for(var i in json){
 setArrayCurr[json[i].TO_CURRENCY] =json[i];
}

this should put your json datas to each section in setArrayCurr array.

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