2011-09-23 99 views
1

這是JSON輸出,我目前有:jQuery的解析JSON

[{"pk": 1, "model": "system.employees", 
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}] 

我所要的輸出是

[{"label": "Eli", "value": "1"}] 

我怎麼能採取的pk和eng_name值從JSON數據並像上面那樣輸出它?

回答

5

您可以使用jQuery.map

var data = [{"pk": 1, "model": "system.employees", 
    "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]; 

var new = $.map(data, function(index, item) { 
     return { label: item.fields.eng_name, value: item.pk }; 
    }); 
1
var result = [{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}] 
var output = [{ "label" : result[0].fields.eng_name, "value": result[0].pk}] 
0
//assuming your source obj is called 'source' 
var num = source[0].pk; 
var eng_name = source[0].fields.eng_name; 

...那麼你可以做任何與他們一樣,

var output = []; 
output.push({"label":eng_name, "value":num}); 

祝你好運!