Ad

Parsing Array Of Objects To Format Data

I have an array of cities with this structure (given from the 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,
    }];

I want to parse the coordinates position to get a more scalable object and get its properties nesting.

This is what I've tried:

cities.map(city=>JSON.parse(city.coordinates))

But when I print it seems to have no effect. However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) it shows a formatted result like is shown in the following screenshot:

enter image description here

How can I make it automatically via loop?

Ad

Answer

This is what I've tried:

cities.map(city=>JSON.parse(city.coordinates))

map() created you a brand new, separate array with the coordinates only, which you have thrown away afterwards.

However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) [...] How can I make it automatically via loop?

Well, put it in a loop:

for(let city of cities)
  city.coordinates = JSON.parse(city.coordinates);


However your example data is syntactically incorrect, there are ,}-s at the end of the objects (after the true/false), and the supposed JSON data is not JSON, like

{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
Ad
source: stackoverflow.com
Ad