Home > Software design >  trying to convert array of list to object?
trying to convert array of list to object?

Time:01-04

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"
          }]
    }

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

try this

 var data={data:{channels: Object.assign(...olddata.details.channels.map(
          obj=> ({[obj.channelType]: JSON.parse(obj.isActive)})))}};

data

{
    "data": {
        "channels": {
            "EM": true,
            "SMS": false
        }
    }
}
  •  Tags:  
  • Related