I have an array of objects:
const action_triggers = [
{
onClick: {
action_id: "1",
},
},
{
onl oad: {
action_id: "2",
},
},
];
How do I convert it into the following by JavaScript?
const action_trigger = {
onClick: {
action_id: 1
},
onl oad: {
action_id: 2
}
}
CodePudding user response:
Here is the reduce version
const _l = (s) => {
console.log(s);
};
let flatter = action_triggers.reduce((propogator, prop) => {
for (const [key, value] of Object.entries(prop)) {
propogator[key] = value;
}
return propogator;
}, {});
_l(flatter);
Helps with conditionally doing whatever you want to {} the input
CodePudding user response:
Try this code:
const action_triggers = [
{
onClick: {
action_id: "1",
},
},
{
onl oad: {
action_id: "2",
},
},
];
let result = {};
action_triggers.forEach((child) => {
Object.entries(child).forEach(([key,{action_id}]) => result[key] = {action_id: parseInt(action_id)})
})
console.log(result)