Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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:

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use reduce:

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

let result = Object.keys(dict).reduce((acc, key) => acc + `${key}=${dict[key]} ` ,'');

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

This line may work for you:

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

const result = Object.entries(dict).map(item => `${item[0]} = '${item[1]}'`).join(' ')

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda