[英]How to change json data format from array to array of objects with javascript?
[英]How to make a Javascript objects from given JSON data format
嗨,我需要帮助了解如何从给定的 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
我创建了以下函数来获取 count 的值:
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 、 loops或任何其他迭代器对其进行迭代。
通常,(通过JSON.parse()
解析字符串后)您可以使用.forEach
函数.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 文档)
编辑:您还可以访问计数器的.map()
函数中的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.