我必须从对象中提取特定数据。我的代码可以工作,但我想知道是否可以通过使用 map 或过滤器等方法来改进它。
此内容不针对任何特定背景,仅用于人员培训。我也在使用 Lodash 库
function extractApi(data) {
var arrayOfTowns = [];
var arrayOfCityCode = [];
var result = [];
//looping throw the expected datas (cities and postcode)
for (var i = 0; i < data.features.length; i++) {
arrayOfCityCode.push(_.toString(data.features[i].properties.postcode));
arrayOfTowns.push(_.toString(data.features[i].properties.city));
//verify unique cities
arrayOfTowns = _.uniq(arrayOfTowns);
//pushing to a new array to have the expected result format
if (arrayOfTowns[i] != undefined && arrayOfCityCode != undefined){
result[i] = arrayOfCityCode[i] + " " + arrayOfTowns[i]
}
}
return result
}
//example with some datas
extractApi( {
"type": "FeatureCollection",
"limit": 20,
"version": "draft",
"licence": "ODbL 1.0",
"attribution": "BAN",
"features": [
{
"type": "Feature",
"properties": {
"importance": 0.6466,
"type": "municipality",
"adm_weight": 4,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43157",
"population": 18.8,
"x": 769600,
"y": 6438600,
"name": "Le Puy-en-Velay",
"citycode": "43157",
"label": "Le Puy-en-Velay",
"city": "Le Puy-en-Velay",
"score": 0.8769636363636364
},
"geometry": {
"coordinates": [
3.883955,
45.043141
],
"type": "Point"
}
},
{
"type": "Feature",
"properties": {
"importance": 0.0867,
"type": "municipality",
"adm_weight": 1,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43089",
"population": 3.6,
"x": 767600,
"y": 6438900,
"name": "Espaly-Saint-Marcel",
"citycode": "43089",
"label": "Espaly-Saint-Marcel",
"city": "Espaly-Saint-Marcel",
"score": 0.8260636363636362
},
"geometry": {
"coordinates": [
3.858597,
45.046041
],
"type": "Point"
}
},
],
"query": "43000"
}
)
目标是接收所有 data.features.properties.postcode
和 data.features.properties.city
并将其推送到数组中。对于此示例,预期结果为 ["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]
。结果中的城市应该是唯一的。
最佳答案
您确实可以使用.map
来获得您想要的结果:
const parsedCities = data.features
.map(f => `${f.properties.postcode} ${f.properties.city}`)
.filter((f, i, a) => a.indexOf(f) === i);
//["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]
您可以在 Array.prototype.map()
here 上找到文档.
关于javascript - 将对象数组转换为其属性的唯一组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57159417/