[英]How to get specific object-elements from JSON-array into JavaScript-array
我有一個外部JSON文件。 看起來像這樣:
{
"type":"FeatureCollection",
"totalFeatures":1,
"features":
[{
"type":"Feature",
"id":"asdf",
"geometry":null,
"properties":
{
"PARAM1":"19 16 11",
"PARAM2":"31 22 11",
"PARAM3":"12 10 7",
}
}],
"crs":null
}`
我認為“ 功能 ”是一個JSON數組,而“ 屬性 ”是此數組的對象。 我堅持嘗試將元素“ PARAM1 ”“ 推入 ”我的JS代碼中的另一個數組中。 我的嘗試是通過jQuery AJAX獲取數據。 看起來像這樣:
function (){
var arrPARAM1 = new Array ();
$.ajax({
async: false,
url: 'gew.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function(data) {
arrPARAM1.push(data.features);
}
})
console.log(arrPARAM1);
}
使用arrPARAM1.push(data.features),我可以將整個數組“ features ”“ 推入 ”我的JS數組中。 但是我只想從對象“ properties ”中獲取元素“ PARAM1 ”。 如何深入了解( 功能 -> 屬性 -> PARAM1 )?
感謝您的關注!
解:
arrPARAM1.push(data.features[0].properties.PARAM1);
它只是一個具有單個元素的數組,因此訪問[0]
然后訪問.properties
arrPARAM1.push(data.features[0].properties.PARAM1);
您將尋找這樣的東西:
data.features[0].properties["PARAM1"]
要么
data.features[0].properties.PARAM1
您將要素定義為數組,因此在訪問要素時,必須將其視為數組。
arrPARAM1.push(data.features[0].properties.PARAM1); //gets param1 from the features array
如果您具有多種功能:
data.features.forEach(function(feature) {
arrPARAM1.push(feature.properties.PARAM1);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.