首页 > 解决方案 > 解析对象数组以格式化数据

问题描述

我有一系列具有这种结构的城市(来自 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))它会显示一个格式化的结果,如下面的屏幕截图所示:

在此处输入图像描述

如何通过循环自动制作它?

标签: javascriptjsonloopsecmascript-6netlify-cms

解决方案


这是我尝试过的:

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

推荐阅读