gpt4 book ai didi

javascript - 从 GeoJson 集合中提取属性和唯一值

转载 作者:行者123 更新时间:2023-11-30 13:57:22 25 4
gpt4 key购买 nike

这是一个 geojson 对象,它有一个特征数组,每个特征都有一个 properties 对象。

我知道有很多与映射数组和对象相关的问题,但我找不到类似的案例。我尝试使用 lodash mapgroupBy 来映射属性并将值分组到它们的 key 下,但老实说我只是不知道是什么应该是功能组合。

我可以通过执行以下操作来获取属性名称部分:

// since properties are the same for all features
// I extract them alone first

let properties = Object.keys(features[0].properties)

properties.map(Prentelement =>
{
let formated = {
// this gives me the first part
propertyName: Prentelement,

// I can't figure out this part to map the values uniquely under
children: [
{
value: "alex"
},
{
value: "cairo"
}
]
}

return formated;
})

这是输入格式的一个例子:

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"Name": "cairo",
"Type": "Province"
}
},
{
"type": "Feature",
"properties": {
"Name": "alex",
"Type": "Province"
}
}
]
}

我想做的是对每个可用属性及其在不同功能中的可能值的一种总结。请注意,一个值可以跨功能重复,但我希望它在最终结果中只可用一次。所以结果将是这样的数组:

[
{
propertyName: "Name",
children: [
{value: "alex"},
{value: "cairo"}
]
},
{
propertyName: "Type",
children: [
{value: "Province"}
]
}
]

最佳答案

这里有一个解决方案,首先使用 Array.reduce()按对象的属性对 features 数组进行分组。注意我们使用 Sets仅保留唯一值。稍后,在第二步,我们可以 Array.map()先前生成的对象的 entries 以获得所需的结构:

let input = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {"Name": "cairo", "Type": "Province"}
},
{
"type": "Feature",
"properties": {"Name": "alex", "Type": "Province"}
}
]
};

// Step 1, group feature values by property.

let out = input.features.reduce((acc, {properties}) =>
{
Object.entries(properties).forEach(([key, val]) =>
{
acc[key] = acc[key] || new Set();
acc[key].add(val);
});

return acc;
}, {});

// Show the generated object on Step 1.

console.log("Step 1 - After grouping:", out);

for (const key in out)
{
console.log(`${key} => ${[...out[key]]}`);
}

// Step 2, map the entries of the generated object.

out = Object.entries(out).map(([k, v]) =>
({PropertyName: k, Children: [...v].map(x => ({Value: x}))})
);

console.log("Step 2 - After mapping:", out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

您可能需要阅读的其他文档:

关于javascript - 从 GeoJson 集合中提取属性和唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com