i am trying to convert array key/value pair to an object using map and formEntries function i am getting an error message:'Object.fromEntries is not a function' any idea about the fix
main.js
const data = {}
const channelsMap = new Map(details.channels);
const channels = Object.fromEntries(channelsMap);
data = channels;
expected output
data : {
channels: {
"EM": true,
"SMS": false
}
}
data
{ details: {
"channels": [
{
"channelType": "EM",
"isActive": "true"
},
{
"channelType": "SMS",
"isActive": "false"
}]
}
You need to reduce the details.channels array into an object where the channelType is the key and the isActive is the value.
const original = {
details: {
channels: [
{ channelType: "EM" , isActive: true },
{ channelType: "SMS" , isActive: false },
]
}
};
const transformed = {
data: {
channels: original.details.channels
.reduce((acc, { channelType, isActive }) =>
({ ...acc, [channelType]: isActive }), {})
}
};
console.log(transformed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upgrading your Node version to something above v12.0.0 should do it. This method isn't included in your current Node version. Documentation here.
first is not allowed to use const when you want to change the value , second this is the code to expected output :
let data = {channels:details.channels.map(channel => ({[channel.channelType] : JSON.parse(channel.isActive) }))};