Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

286
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!