這是JSON輸出,我目前有:jQuery的解析JSON
[{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
我所要的輸出是
[{"label": "Eli", "value": "1"}]
我怎麼能採取的pk和eng_name值從JSON數據並像上面那樣輸出它?
這是JSON輸出,我目前有:jQuery的解析JSON
[{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
我所要的輸出是
[{"label": "Eli", "value": "1"}]
我怎麼能採取的pk和eng_name值從JSON數據並像上面那樣輸出它?
您可以使用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 };
});
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}]
//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});
祝你好運!
嘗試 -
var h = JSON.parse('[{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]');
var a = [];
a.push({"label": h[0].fields.eng_name, "value": h[0].pk+''})
alert(JSON.stringify(a))
NB你需要導入這個代碼 - https://github.com/douglascrockford/JSON-js/blob/master/json2.js如果你的瀏覽器不支持JSON.parse
和JSON.stringify