Search code examples
javascriptarraysobjectkey-valuecustom-object

Convert array into custom object with array items as key values


I'm kinda new to JS so I kinda got stuck with this what it seemed simple problem. I have to convert payload from:

const payload = {left: ['name', 'phone'], right: ['address']} 

to:

const payload = 
  columns: {
      name: {
        pinned: 'left',
      },
      phone: {
        pinned: 'left',
      },
      address: {
        pinned: 'right'
     }
    },

So far i came up with something like this:

const left = pinnedColumns.left.map((col) => ({ [col]: { pinned: 'left' } }));

But it creates an array with index as a key.


Solution

  • You can do this pretty cleanly with a for and forEach loop:

    const payload = {
      left: ['name', 'phone'],
      right: ['address']
    }
    
    const result = {columns: {}};
    for(const [key, val] of Object.entries(payload)) {
      val.forEach(v => {
        result.columns[v] = {pinned: key};
      });
    }
    console.log(result);