简体   繁体   English

如何将特定的对象元素从JSON数组转换为JavaScript数组

[英]How to get specific object-elements from JSON-array into JavaScript-array

I have an external JSON-file. 我有一个外部JSON文件。 It looks like this: 看起来像这样:

{
"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
}`

As I think " features " is an JSON-array and " properties " an object of this array. 我认为“ 功能 ”是一个JSON数组,而“ 属性 ”是此数组的对象。 I stuck at trying to " push " the element " PARAM1 " into another array in my JS-code. 我坚持尝试将元素“ PARAM1 ”“ 推入 ”我的JS代码中的另一个数组中。 My attempt was to get the data via jQuery AJAX. 我的尝试是通过jQuery AJAX获取数据。 It looks like this: 看起来像这样:

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);
}

With arrPARAM1.push(data.features) I can " push " the whole array " features " into my JS-array. 使用arrPARAM1.push(data.features),我可以整个数组“ features ”“ 推入 ”我的JS数组中。 But I only want to have the element " PARAM1 " from the object " properties ". 但是我只想从对象“ properties ”中获取元素“ PARAM1 ”。 How can I get deeper ( features --> properties --> PARAM1 )? 如何深入了解( 功能 -> 属性 -> PARAM1 )?

Thanks for your attention! 感谢您的关注!


SOLUTION: 解:

arrPARAM1.push(data.features[0].properties.PARAM1);

它只是一个具有单个元素的数组,因此访问[0]然后访问.properties

arrPARAM1.push(data.features[0].properties.PARAM1);

You would be looking for something like this: 您将寻找这样的东西:

data.features[0].properties["PARAM1"]

Or 要么

data.features[0].properties.PARAM1

您将要素定义为数组,因此在访问要素时,必须将其视为数组。

arrPARAM1.push(data.features[0].properties.PARAM1); //gets param1 from the features array

In case you have multiple features: 如果您具有多种功能:

data.features.forEach(function(feature) {
    arrPARAM1.push(feature.properties.PARAM1);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM