0

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

2 Answers 2

2

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' */ ]
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.