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

Map array or object to array improvement

Question is simple, I have an object property content.categories that may be an array or a single object.

In any case, I’d like to create a new array containing the id/ids.

What I’m doing here is checking if property is an array, otherwise add the object into an array and finally map it.

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

Is there any way to improve this code? Feels ugly to me but I didn’t find a way to make ir shorter.

categoriesIds = Array.isArray(content.categories) 
      ? content.categories?.map((category) => category.id) 
      : [content.categories]?.map((category) => category.id)

>Solution :

You could concat with an empty array and value/items. The result is always a flat array of the first level.

categoriesIds = [].concat(content.categories).map(({ id }) => id);
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