如何将新数据添加到geoJson文件



我想在"gj";从";dataToAdd";。";gj为:

const gj = {
"type": "FeatureCollection", "features" : [
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 1,
"DS_ID" : 1
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 2,
"DS_ID" : 3
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 3,
"DS_ID" : 2
}
},
]
}

&dataToAdd的格式为:

const dataToAdd = [
{
"ds_id": 3,
"value": 10
},
{
"ds_id": 1,
"value": 20
},
{
"ds_id": 2,
"value": 30
},
]

我需要以下格式的输出:

requireOutput = {
"type": "FeatureCollection", "features" : [
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 1,
"DS_ID" : 1,
"value": 20
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 2,
"DS_ID" : 3,
"value": 10
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 3,
"DS_ID" : 2,
"value": 30
}
},
]
}

我可以在属性中添加数据,但我很难实现我想要的:

let requireOutput = [];
for(let i =0; i<gj.features.length; i++) {
const properties = gj.features[i].properties
requireOutput.push({
...properties,
...dataToAdd.find((item) => item.ds_id === properties.DS_ID)
})
}
console.log(requireOutput)

如何添加类型&几何学我知道我只是缺少一个小逻辑。我抓不住。

试试这个

let requireOutput = JSON.parse(JSON.stringify(gj));// For Deep Cloning so that gj does not get changed
for (i of requireOutput.features) 
i.properties.value = dataToAdd.find((item) => item.ds_id === i.properties.DS_ID).value

const gj = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 1,
"DS_ID": 1
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 2,
"DS_ID": 3
}
},
{
"type": "Feature",
"geometry": {
"type": "Ploygon",
"coordinates": ["coordinates"]
},
"properties": {
"OBJECTID": 3,
"DS_ID": 2
}
},
]
}
const dataToAdd = [{
"ds_id": 3,
"value": 10
},
{
"ds_id": 1,
"value": 20
},
{
"ds_id": 2,
"value": 30
},
]
let requireOutput = JSON.parse(JSON.stringify(gj)); // For Deep Cloning so that gj does not get changed
for (i of requireOutput.features) 
i.properties.value = dataToAdd.find((item) => item.ds_id === i.properties.DS_ID).value
console.log(requireOutput);

另外-如果你想编辑你的功能,试试这个

let requireOutput = JSON.parse(JSON.stringify(gj))
for (let i = 0; i < requireOutput.features.length; i++) {
const properties = requireOutput.features[i].properties
requireOutput.features[i].properties = {
...properties,
...dataToAdd.find((item) => item.ds_id === properties.DS_ID),
}
}

最新更新