How to convert array to object in Javascript?

Viewed 109

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}})})

3 Answers

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 }))));

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

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: '' }
Related