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:
JavaScript
x
6
1
var dict = {
2
rel: 'preload',
3
as: 'image',
4
type: 'image/webp'
5
}
6
And I am trying to parse it into a query string converting it into:
JavaScript
1
2
1
return "rel='preload' as='image' type='image/webp'"
2
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:
JavaScript
1
2
1
Object.keys(dict).forEach(key => console.log(`${key}="${dict(key)}"`) )
2
How do i concatinate the result of that in the same line? Is it possible? I have been trying with:
JavaScript
1
5
1
.reduce()
2
.push()
3
.concat()
4
.join()
5
but can’t seem to get it to work in one line.
Advertisement
Answer
This is one way to obtain the desired result.
JavaScript
1
10
10
1
const dict = {
2
rel: 'preload',
3
as: 'image',
4
type: 'image/webp'
5
};
6
console.log(
7
Object.entries(dict)
8
.map(([k, v]) => (`${k}='${v}'`))
9
.join(' ')
10
);
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