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