我正在尝试将GeoJSON映射文件与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": [...]
}
}
]
}
{
"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地图格式。
答案 0 :(得分:2)
您可以在features数组上循环,并检查zipcode
上的data2
值是否存在(将其添加到相应元素的属性中)
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)
答案 1 :(得分:2)
尝试一下:
let data1 = {"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,}}
data1.features.map(res => Object.assign(res, {
properties: {
...res.properties,
...data2[res.properties.ZIPCODE]
}
}))
console.log(data1)