Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda