How can I return array from array using map?

Viewed 20

Lets say I have an array:

[['name', 'bulb'],['color', ['red', 'green', 'blue']],[price, ['$52']]]

If I use

array.map(([key, value]) => `${key}-${value}`)

it will return me array:

['name-bulb', 'color-red,green,blue', 'price-$52']

however, I want it to return

['name-bulb', 'color-red', 'color-green', 'color-blue', 'price-$52']

how can I do that?

1 Answers

You can use flatMap instead with a nested map

const data = [['name', 'bulb'],['color', ['red', 'green', 'blue']],['price', ['$52']]]

const result = data.flatMap(([name, value]) => 
  (Array.isArray(value) ? value : [value]).map(value => `${name}-${value}`)
)

console.log(result)

Related