2016-06-08 103 views
0

我是jQuery的新手,我正在嘗試使用getJSON函數。我想要做的是拉JSON文件的「id」部分,並將其推入jQuery中名爲planes的數組中。從那裏,該數組用於自動填充功能來填充可搜索的ID。如何使用jQuery將JSON數據推送到數組中?

var planes = []; 
$.getJSON('planes.json', function(data) { 
    console.log('Filling array...'); 

//This is where I think the issue is occurring. 
//Is using the name of the section you want to use the correct syntax here? 
    $.each(data.id, function (index, val) { 
     planes.push(val.id); 
     console.log('Pushed ' + index); 
    }); 
}); 

// After getJSON, array should look something like this: 
// var planes = [ 
// 'Alara', 
// 'Fiora', 
// 'Innistrad', 
// 'Kamigawa', 
// 'Lorwyn', 
// 'Mirrodin', 
// 'Ravnica', 
// 'Shandalar', 
// 'Zendikar' 
// ]; 

的JSON文件安排像這樣:

[ 
    {"id": "Ravnica"}, 
    {"id": "Lorwyn"}, 
    {"id": "Innistrad"}, 
    {"id": "Zendikar"}, 
    {"id": "Kamigawa"}, 
    {"id": "Mirrodin"}, 
    {"id": "Shandalar"}, 
    {"id": "Alara"}, 
    {"id": "Fiora"} 
] 

Plunker

任何幫助深表感謝。

+0

順便說一句,你使用mtgjson.com的數據集?如果沒有,那可以爲你的項目節省很多時間...... –

回答

1

你幾乎已經擁有了它,雖然你正在循環着data.id這不是你想要做的。您應該循環訪問data,然後按val.id

如果你想遍歷data.id,那麼你JSON必須像這樣被結構化:

{ 
    "id": [ 
     "things", 
     "to", 
     "loop", 
     "through" 
    ] 
} 

..但它不是,所以只是通過數據循環。

+1

就是這樣!謝謝你的幫助。此外,它看起來像我可以有不同的結構我的JSON,使這更容易一些。 – Thassa

+1

很高興聽到:3 – bitten

0

請檢查以下解決方案。我有硬編碼的平面數據,而不是從文件中獲取,但解決方案是相同的。你只需要通過遍歷數據而不是data.id來更新你的$ .each行(這是你的錯誤代碼的其餘部分很好)。

var data = [{ 
 
    "id": "Ravnica" 
 
}, { 
 
    "id": "Lorwyn" 
 
}, { 
 
    "id": "Innistrad" 
 
}, { 
 
    "id": "Zendikar" 
 
}, { 
 
    "id": "Kamigawa" 
 
}, { 
 
    "id": "Mirrodin" 
 
}, { 
 
    "id": "Shandalar" 
 
}, { 
 
    "id": "Alara" 
 
}, { 
 
    "id": "Fiora" 
 
}]; 
 
var planes = []; 
 
//surround this each with your $.getJSON. I have just hardcoded json data instead of getting it from file 
 
$.each(data, function(index, val) { 
 
    planes.push(val.id); 
 
}); 
 

 
console.log(planes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你更新plunker鏈接Plunker

0

你也可以考慮本地陣圖的方法,它可以節省您不必創建一個數組,然後推到的東西它。它只是通過在每個項目上應用映射函數而返回給定原始數組的新數組。

$.getJSON("planes.json",function(data){ 
    console.log(data.map(function(plane){return plane.id;})) 
} 

但是,如果我正確記得,這是不可用在IE < = 8。

相關問題