Ollie Ollie - 27 days ago 9
Javascript Question

Lodash complicated key value replace

I am using lodash/_, and I'd like to generate the following output from the input JSON.

Any input on how to achieve this, would be great.

Input:

{
"hex": "#EFDECD",
"name": "Almond",
"rgb": "(239, 222, 205)"
},
{
"hex": "#CD9575",
"name": "Antique Brass",
"rgb": "(205, 149, 117)"
},


Desired Output:

{
Almond: '#EFDECD',
Antique Brass: '#CD9575',
...
};


Thanks for your time

Answer Source

Use can use Array.prototype.reduce method for this:

let data = [{
  "hex": "#EFDECD",
  "name": "Almond",
  "rgb": "(239, 222, 205)"
},
{
  "hex": "#CD9575",
  "name": "Antique Brass",
  "rgb": "(205, 149, 117)"
}];

let newData = data.reduce((result, elem) => {
    result[elem.name] = elem.hex
    return result;
}, {});