Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create an object mapping from an array of strings?

i am stumbling onto something that should be easy, yet i can’t seem to be able to do it.

i have an array of string, and i want to map over it to create an object like so :

const monthesList = ['january', 'february', 'march', 'april', 'may']

const myState = monthesList.map(month => (
    month: {selected: true, year: 2022}
    )
  )

what i want is to get the following object :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

myState ={
  january:{ 
    selected: false,
    year: 2022
  },
  february:{ 
    selected: false,
    year: 2022
  },
  march:{ 
    selected: false,
    year: 2022
  },
  april:{ 
    selected: false,
    year: 2022
  },
  may:{ 
    selected: false,
    year: 2022
  },
}

Edit:
i just found the way :

const myState = monthesList.map(month => (
    {[month] : {
      selected: false,
      year: 2022
    }}
    )
  )

just need to make an object out of it, shouldn’t be too hard

>Solution :

The .map() method returns an array, but the output that you’re after is an object. You need something that can convert an array of key-value pairs (ie: [key, value]) to an object. For this, we have the Object.fromEntries() method that takes an array of key-value pairs, and from it, constructs an object like so:

const monthesList = ['january', 'february', 'march', 'april', 'may'];

const myState = Object.fromEntries(monthesList.map(month => [
  month, {selected: true, year: 2022}
]));
console.log(myState);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading