cal
cal

Reputation: 1873

Turn keys and values into a string javascript

I want to concatenate the keys and values of an object into a string with certain rules when joining each string. The object looks like this:

{ sm: "column", md: "row", lg: "row"}

Ideally I would like turn it into string resembling this:

"sm-column md-row lg-row".

I'm struggling with a way to join the arrays with different rules. Any pointers would be much appreciated.

const direction = { sm: 'column', md: 'row', lg: 'row'}

const result = Object.entries(direction).flat().join(" ")

console.log(result)

Upvotes: 0

Views: 54

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

You were very close. Just one small change is needed. Instead of using .flat() to put the keys and values together in one big array, first use map to join each inner array with a "-" before joining the inner arrays with a space. (Note I used a template literal with an anonymous function to do the inner join here, but I could easily have used .join("-") instead. Neither is better than the others, it was just the first thing that occurred to me.)

const direction = { sm: 'column', md: 'row', lg: 'row'}

const result = Object.entries(direction).map(([key, value]) => `${key}-${value}`).join(" ")

console.log(result)

Upvotes: 2

Related Questions