简体   繁体   English

将json推入不同数组的更好方法

[英]better way to push json into different array

i want to push my json into different array. 我想将json推送到其他数组中。

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. 在我在for循环内使用if函数之前,它可以正常工作,但是我想知道是否有一个更简单的方法,因为如果我有很多数组,那么我的循环内将有很多if函数。

part of my json 我的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. 这是因为您已将setArrayCurr设置为字符串而非数组。

which means every time you declare setArrayCurr, it will change its context but not add nor categorize it. 这意味着每次您声明setArrayCurr时,它都会更改其上下文,但不会添加它或对其进行分类。

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. 这应该将您的json数据放入setArrayCurr数组中的每个部分。

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

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