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?
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);
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.