How do I use map() on an object array that has a periods in its object keys? Index notation doesn't work

I thought for sure this would have been asked before, I tried searching but feel free to point me in the right direction.

So here’s the problem data, lets call it "data":

[
{
   "Wetlands.WETLAND_TYPE": "Freshwater Forested/Shrub Wetland"
},
{
   "Wetlands.WETLAND_TYPE": "Lake"
},
{
   "Wetlands.WETLAND_TYPE": "Riverine"
}
]

JS:

const myWetlands = data.map(({ Wetlands.WETLAND_TYPE }) => Wetlands.WETLAND_TYPE);
console.log(myWetlands);

Obviously, it doesn’t escape the periods in Wetlands.WETLAND_TYPE – so the logical next choice was to use ["index notation"] on it, but that doesn’t work as it doesn’t allow the brackets.

I know the data has awful presentation, but that’s what it is at the source (blame the USFWS). I wonder if there is a better API for wetlands that I haven’t found…

Is there any way to use map() here when the keys I want have periods in them?

>Solution :

This doesn’t use destructuring like your example, but seems to do the job you are looking for.

const origArray =  [
{
   "Wetlands.WETLAND_TYPE": "Freshwater Forested/Shrub Wetland"
},
{
   "Wetlands.WETLAND_TYPE": "Lake"
},
{
   "Wetlands.WETLAND_TYPE": "Riverine"
}
]

const myWetlands = origArray.map(item => item[ "Wetlands.WETLAND_TYPE"]);
console.log(myWetlands);

Leave a Reply