2

I have a nested object which looks like the below

{
    "Place One": {
        primary: "#000000",
        secondary: "#97233f",
        coordinates: {
            lat: 49.5013,
            lon: 87.0622
        }
    },
    "Place Two": {
        primary: "#000000",
        secondary: "#a71930",
        coordinates: {
            lat: 40.6013,
            lon: 81.0622
        }
    },
    "Place Three": {
        primary: "#9e7c0c",
        secondary: "#241773",
        coordinates: {
            lat: 40.5033,
            lon: 84.0622
        }
    }
}

I am trying to get access to each of the lat /lon variables to pass to a Leaflet React component

 <Marker
          key={park.properties.PARK_ID}
          position={[
            ***the lat***,
            ***the lon***
          ]}
        
        />

I've tried the below:

Object.fromEntries(
                Object.entries(teams).map(([key, { coordinates }]) => <Marker
                    position={[
                        coordinates.lat,
                        coordinates.lon
                    ]} />
                )

but cannot access the values.

can anyone please advise the best way to do this?

Stuart Brown
  • 977
  • 2
  • 22
  • 47

2 Answers2

1

Let's say your data structure containing your nested objects is assigned to a "data" variable:

const data = {
  "Place One": {}, // etc.
}

Then in your React component template, you can loop over the "nested objects" with:

Object.keys(data).map((key) => {
  const nestedObject = data[key]
  return (<Marker
    key={key}
    position={nestedObject.coordinates} // or [nestedObject.coordinates.lat, nestedObject.coordinates.lon]
  />)
})
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • i think in the OP's code if the whole Object.fromEntries wrapping is removed it should still work? – cmgchess Mar 09 '22 at 19:28
  • @cmgchess yes, you're right. const newObj = Object.entries(team).map(([key, { coordinates }]) => [coordinates.lat,coordinates.lon] ) works – Stuart Brown Mar 09 '22 at 21:29
0

I Believe you should destructurate the nested object starting like this

const obj1 = your_nested_object
const lat = obj1.Place_One.coordinates.lat
const lon = obj1.Place_One.coordinates.lon