2017-08-18 25 views
-1

enter image description here輸入:var result= JSON.parse(response); console.log(result);將ajax響應轉換爲特定格式?

以下給出的是console.log(result)的輸出。現在我想將其轉換爲下面給出的輸出,我想這樣。

Output:  
    {day: Array(7), amount: Array(7)} 
    amount: (7) [413, 14, 2, 37, 50, 22, 82] 
    day: (7) ["02-Jan-16", "03-Jan-16", "04-Jan-16", "05-Jan-16", "06-Jan-16", 
    "07-Jan-16", "08-Jan-16"] 


This input is ajax response data. Now i want to convert this response data 
into a particular format which i describe below. My output should look like 
this. How can i do this? 


Output I want: 

[[02-Jan-16,413],[03-Jan-16,14],[04-Jan-16,2],[05-Jan-16,37], [06-Jan- 
16,50],[07-Jan-16,22],[08-Jan-16,82]] 

enter image description here 這是輸出圖像。一探究竟。

+2

請添加原始字符串。 –

回答

0

您可以映射新數組的所需值。

function getData(object) { 
 
    return data.amount.map(function(a, i) { 
 
     return [object.day[i], a]; 
 
    }); 
 
} 
 

 
var data = { 
 
     amount: [413, 14, 2, 37, 50, 22, 82], 
 
     day: ["02-Jan-16", "03-Jan-16", "04-Jan-16", "05-Jan-16", "06-Jan-16", "07-Jan-16", "08-Jan-16"] 
 
    }, 
 
    result = getData(data); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

在此您正在靜態定義數據。我在ajax響應對象中有這個數據。現在如何轉換這個。 –

+0

您可以將功能放入函數中並在必要時調用它。 –

+0

這裏是針對特定的數據格式。這裏你知道鑰匙。我不希望我的代碼像這一天特定於此鍵。如果我根據數據庫獲取密鑰不同的數據,那麼它不起作用。 –

1

首先,你必須決定以何種語言,你想要做的JSON編碼PHP或JavaScript?有兩種語言都可以使用內置函數,首先您應該熟悉嵌套數組,一旦理解了數組構造,然後只需幾分鐘即可使用內置函數形成預期的JSON格式。

請不要期望我們的代碼,當已經有大量的信息在網上,只是谷歌它。

相關問題