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

2
  • 3
    Possible duplicate of Convert Array to Object Commented Jan 11, 2019 at 8:05
  • 1
    .map returns an array, spreading it into an object will result in numeric-indexed properties. Commented Jan 11, 2019 at 8:08

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.