嗨,我需要幫助了解如何從給定的 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)
感謝并感謝任何輸入
uj5u.com熱心網友回復:
我建議您使用JSON.parse()將 JSON 字串轉換為純 JS 物件。
之后,您可以使用for...in、loops或任何其他迭代器對其進行迭代。
uj5u.com熱心網友回復:
通常,(通過 決議您的字串后JSON.parse())您可以Object.feature使用該.forEach函式遍歷您的陣列(請參閱 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()計數器的函式內的索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/353639.html
標籤:javascript 反应 json 目的
上一篇:JavaScript:如何使變數以給定的速度逐漸接近目標值?
下一篇:JS設計模式-執行不同任務的界面
