2

I have the following array:

const x = [
    {event: "oninput", action: ""},
    {event: "onfocus", action: ""}
]

Following is the desired output:

// event: action
{
    oninput: "",
    onfocus: ""
}

I tried the following which didn't really work:

const x = [
    {event: "oninput", action: ""},
    {event: "onfocus", action: ""}
]

console.log({...x.map(y => {return {[y.event]: y.action}})})
Axel
  • 4,365
  • 11
  • 63
  • 122

3 Answers3

6

You could use Object.assign and map the objects. This collects all objects and assign it to a single object.

const x = [
    { event: "oninput", action: "" },
    { event: "onfocus", action: "" }
];

console.log(Object.assign(...x.map(({ event, action }) => ({ [event]: action }))));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use reduce to build a new object. It also gives compatibility back to ECMAScript 2011:

var x = [
    {event: "oninput", action: ""},
    {event: "onfocus", action: ""}
];

var o = x.reduce((acc, obj) => {acc[obj.event] = obj.action; return acc}, {});

console.log(o);
RobG
  • 142,382
  • 31
  • 172
  • 209
0

Different approach:

const x = [
    {event: "oninput", action: ""},
    {event: "onfocus", action: ""}
]
let newObj = {}
x.forEach(obj => {
    newObj[obj.event] = obj.action
})


console.log(newObj)
// returns { oninput: '', onfocus: '' }
Happy Machine
  • 987
  • 8
  • 30