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

285
Visualizações
How to map just the values in an object, but keep the keys?

I wrote this to convert an object of type

{
  3: "#e3e3e3"
}

into

{
  3: {r: 227, g: 227, b: 227}
}

The code:

  const colorMapInRgb = Object.fromEntries(
    Object.entries(colorMapInHex).map(
      ([value, hex]) => [value, hexToRgb(hex)]
    )
  )

Is there perhaps a more idiomatic way to do it? Maybe a lodash function?

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

0

You can iterate through your object and convert each value into red, green and blue integer value inside an array#map.

const input = { 3: "#e3e3e3", 'red': "#FF0000" },
      result = Object.fromEntries(
        Object.entries(input).map(([key, value]) => {
          const [r, g, b] = value.substr(1,6).match(/..?/g).map(x => parseInt(x, 16));  
          return [key, {r, g, b}];
        })
      );
console.log(result);

Another solution using array#reduce.

const input = { 3: "#e3e3e3", 'red': "#FF0000" },
          result = Object.entries(input).reduce((o, [key, value]) => {
              const [r, g, b] = value.substr(1,6).match(/..?/g).map(x => parseInt(x, 16));  
              o[key] = {r, g, b};
              return o;
            }, {});
    console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Short answer: No, there isn't.

Long answer: There actually still isn't a more idiomatic way to do it, but you can do the same using different syntaxes/functions with basically the same result:

const colorMapInRgb = {};
for (const key in colorMapInHex)
    colorMapInRgb[key] = hexToRgb(colorMapInHex[key]);

// basically same as above
const colorMapInRgb = {};
Object.keys(colorMapInHex).forEach(key => ...);

// Reducing the entries into an object
const colorMapInRgb = Object.entries(colorMapInHex)
    .reduce((result, [k, v]) => ({ ...result, [k]: hexToRgb(v) }), {});

// Reducing the entries into an object but reusing the same object
const colorMapInRgb = Object.entries(colorMapInHex)
    .reduce((result, [k, v]) => (result[k] = hexToRgb(v), result), {});

Again, there isn't really a better way of doing it, it's just preferred syntax.

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