如何从给定的JSON数据格式中生成Javascript对象



嗨,我需要帮助了解如何从给定的JSON数据创建对象:

{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"properties":{
"dbh":6
},
"geometry":{
"type":"Point",
"coordinates":[
-79.96474,
40.46283
]
}
},
{
"type":"Feature",
"properties":{
"dbh":2
},
"geometry":{
"type":"Point",
"coordinates":[
-80.00949,
40.42532
]
}
},
{
"type":"Feature",
"properties":{
"dbh":12
},
"geometry":{
"type":"Point",
"coordinates":[
-79.93531,
40.42282
]
}
}

我做了以下事情:

let rsuCountsData = await axios.get('https://rsu-manager-apigateway 5xm3e3o5.uc.gateway.dev/rsucounts');
this.createGeoJson(rsuCountsData.data); //calling the below function

我创建了以下函数来获取计数的值:

createGeoJson(data){
//geojson={}
//extract the count from data and store it in a object
for (let [key, value] of Object.entries(data)) {
console.log(key, value.count); //key= ip address

}

}

现在,在这个函数中,我想从上面的JSON数据创建对象,但我不确定如何做到这一点,因为它看起来太嵌套了,我无法理解。以下是我所做的。它是伪代码和JS的混合体。也不认为这是正确的,但有人能帮我指出正确的方向吗?我如何在createGeoJson函数中的JS对象中存储这些值:

geojson = {}
geojson.type = "FeatureCollection"
geojson.features = []
for key, val in data:
feat.type = "Feature"
props.count = val.count
props.ipAddress = val.ipAddress// this is the key in above function.
feat.properties = props
geojson.features.append(feat)

感谢并感谢的任何输入

我建议您使用JSON.parse((将JSON字符串转换为纯JS对象。

之后,您可以使用for对其进行迭代。。。in、循环或任何其他迭代器。

通常,(通过JSON.parse()解析字符串后(可以使用.forEach函数在Object.feature数组上循环(请参阅MDN文档(。

不能100%确定您的确切输出应该是什么,但这看起来是.map()函数的一个很好的用例(此处为MDN文档(。比方说,您将JSON存储在const json中,您可以执行以下操作:

const json = { ... }
const newArray = json.features.map(el => Object.assign({},{type: el.type, properties: el.properties, geoType: el.geometry.type}));

newArray将填充由空对象创建的对象和Object.assign()功能(MDN文档(

EDIT:您还可以访问计数器的.map()函数中的索引。

最新更新