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

Is there a one-liner to concatenate the key and values of a dict of unknown size into a string in JS?

I am trying to parse a dictionary into a string in one line as elegantly as possible.

The string could have anywhere from 1 key value pair to 10.

The dictionary I have:

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

var dict = {
  rel: 'preload', 
  as: 'image', 
  type: 'image/webp'
}

And I am trying to parse it into a query string converting it into:

return "rel='preload' as='image' type='image/webp'"

I know that using Object.keys and forEach i can traverse the Dict but how do i concatinate it as well in the same statement?

This is how far i have gotten:

Object.keys(dict).forEach(key => console.log(`${key}="${dict(key)}"`) ) 

How do i concatinate the result of that in the same line? Is it possible?
I have been trying with:

.reduce()
.push()
.concat()
.join()

but can’t seem to get it to work in one line.

>Solution :

This is one way to obtain the desired result.

const dict = {
  rel: 'preload', 
  as: 'image', 
  type: 'image/webp'
};
console.log(
  Object.entries(dict)
  .map(([k, v]) => (`${k}='${v}'`))
  .join(' ')
);

It uses

  • Object.entries() – to obtain key-value pairs from object
  • .map() – to iterate over key-value pairs
  • backtick ` – to transform each pair to desired structure
  • .join() – to finally transform the array into a string
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