Home > OS >  How do I use map() on an object array that has a periods in its object keys? Index notation doesn�
How do I use map() on an object array that has a periods in its object keys? Index notation doesn�

Time:08-06

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?

CodePudding user response:

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);

CodePudding user response:

Here it is with destructuring, but where during destructuring the name of the prop with the . in it is renamed to value.

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

    const myWetlands = origArray.map(({ 'Wetlands.WETLAND_TYPE': value }) =>  value);
    console.log(myWetlands );

  • Related