我正在尝试将 GeoJSON map 文件与 JSON 文件中的键值相结合,以用于等值线图。
这是文件的样子:
data1.json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"STATE": "06",
"ZIPCODE": "94601"
},
"geometry": {
"type": "Polygon",
"coordinates": [...]
}
},
{
"type": "Feature",
"properties": {
"STATE": "06",
"ZIPCODE": "94501"
},
"geometry": {
"type": "Polygon",
"coordinates": [...]
}
}
]
}
data2.json
{
"94501": {
"crime": 172,
"income": 9456,
},
"94601": {
"crime": 118,
"income": 28097,
}
这是我希望组合对象的样子:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"STATE": "06",
"ZIPCODE": "94601",
"crime": 118,
"income": 28097
},
"geometry": {
"type": "Polygon",
"coordinates": [...]
}
},
{
"type": "Feature",
"properties": {
"STATE": "06",
"ZIPCODE": "94501",
"crime": 172,
"income": 9456
},
"geometry": {
"type": "Polygon",
"coordinates": [...]
}
}
]
}
目前,我的代码如下所示:
d3.json("data1.json", function (geoData) {
d3.json("data2.json", function (zipdata) {
var geoFeatures = geoData.features;
for (var i = 0; i < geoFeatures.length; i++) {
Object.keys(zipdata).forEach(function (key) {
if (geoFeatures[i].properties.ZIPCODE == key) {
var combined = Object.assign({}, geoFeatures[i], zipdata[key]);
console.log(combined);
}
})
}
})
})
这让我接近我想要的,但我想保留 data1.json
中显示的 GeoJSON map 格式。
最佳答案
您可以在特征数组上循环并检查 data2
上的 zipcode
值(如果存在)将其添加到相应元素的属性中
let obj = {"type": "FeatureCollection","features": [{"type": "Feature","properties": {"STATE": "06","ZIPCODE": "94601"},"geometry": {"type": "Polygon","coordinates": "[...]"}},{"type": "Feature","properties": {"STATE": "06","ZIPCODE": "94501"},"geometry": {"type": "Polygon","coordinates": "[...]"}}]}
let data2 = {"94501": {"crime": 172,"income": 9456,},"94601": {"crime": 118,"income": 28097,}}
obj.features.forEach(val => {
let { properties } = val
let newProps = data2[properties.ZIPCODE]
val.properties = { ...properties, ...newProps }
})
console.log(obj)
关于javascript - 如何将 json 文件中的键值组合到 geojson map 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432468/