1

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 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.