javascript - 解析对象数组以格式化数据
问题描述
我有一系列具有这种结构的城市(来自 CMS):
const cities = [
{
city: 'Genova',
coordinates: '{\'type\':\'Point\',\'coordinates\':[8.9473343,44.4023918]}',
countryIsoCode: 'it',
description: 'test',
isInitialCity: true,
}, {
city: 'Barcelona',
coordinates: '{\'type\':\'Point\',\'coordinates\':[2.0951271,41.3397004]}',
countryIsoCode: 'es',
description: 'description',
isInitialCity: false,
}, {
city: 'Sydney',
coordinates: '{type\':\'Point\',\'coordinates\':[151.2158203,-33.8704156]}',
countryIsoCode: 'au',
description: 'Sydney description',
isInitialCity: false,
}];
我想解析coordinates
位置以获得更具可扩展性的对象并使其属性嵌套。
这是我尝试过的:
cities.map(city=>JSON.parse(city.coordinates))
但是当我打印它似乎没有效果。但是,如果我手动打印一个位置,console.log(JSON.parse(cities[0].coordinates))
它会显示一个格式化的结果,如下面的屏幕截图所示:
如何通过循环自动制作它?
解决方案
这是我尝试过的:
cities.map(city=>JSON.parse(city.coordinates))
map()
为您创建了一个全新的、单独的数组,仅包含坐标,之后您将其丢弃。
但是,如果我手动打印像
console.log(JSON.parse(cities[0].coordinates))
[...] 这样的位置,如何通过循环自动打印?
好吧,把它放在一个循环中:
for(let city of cities)
city.coordinates = JSON.parse(city.coordinates);
,}
但是,您的示例数据在语法上不正确,对象末尾
有-s (在true
/之后false
),并且假定的 JSON 数据不是 JSON,例如
{type':'Point','coordinates':[151.2158203,-33.8704156]}
^it has no pair, and it should be double quote anyway, all of them
{"type":"Point","coordinates":[151.2158203,-33.8704156]} <-- this is JSON
推荐阅读
- javascript - 保护硒免受检测
- python - 相当于 dask-ml 中 scikit-learn 的 GroupShuffleSplit?
- javascript - 反应倒计时计时器仅在 EST 上运行
- php - 如何在 localhost 中启用 gzip xampp?
- c# - Cassandra.ServerErrorException:'java.lang.NoClassDefFoundError:org/joda/time/ReadablePartial'
- angular - 在 angular5 中使用 *ngFor 获取特定值
- ftps - Duplicity 不适用于 lftp+ftps 后端
- html - 如何根据标签文本的宽度使html标签和输入框宽度相同
- python - 如何将 yapf 应用于目录下的每个 python 文件?
- git - 从一个分支移植到另一个分支