[英]better way to push json into different array
我想將json推送到其他數組中。
在我在for循環內使用if函數之前,它可以正常工作,但是我想知道是否有一個更簡單的方法,因為如果我有很多數組,那么我的循環內將有很多if函數。
我的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"},
現在我在循環中有什么
if(json[i].TO_CURRENCY == 'TWD'){
arrayApp.TWD.push(json[i]);}
if(json[i].TO_CURRENCY == 'HKD'){
arrayApp.HKD.push(json[i]);}
因為我有很多不同的貨幣,我不得不寫很多東西
這是我在想的但似乎沒有用
var setArrayCurr='';
for ( i in json ) {
setArrayCurr=json[i].TO_CURRENCY
arrayApp.setArrayCurr.push(json[i]);
} //end of loop
嘗試這個:
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
最終結果將是按貨幣分組的多個數組:
{
"AWD": [ /* all jsons with currency 'AWD' */ ],
"TWD": [ /* all jsons with currency 'TWD' */ ],
"HKD": [ /* all jsons with currency 'HKD' */ ]
...
}
這是因為您已將setArrayCurr設置為字符串而非數組。
這意味着每次您聲明setArrayCurr時,它都會更改其上下文,但不會添加它或對其進行分類。
var setArrayCurr = [];
for(var i in json){
setArrayCurr[json[i].TO_CURRENCY] =json[i];
}
這應該將您的json數據放入setArrayCurr數組中的每個部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.