Home > Mobile >  Convert array into custom object with array items as key values
Convert array into custom object with array items as key values

Time:11-25

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.

CodePudding user response:

This could be solved with a reduce function:

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

const result = Object.entries(payload).reduce((acc, [key, values]) => {
  for (const value of values) {
    acc.columns[value] = {pinned: key}
  }
  return acc
}, {columns: {}})

console.log(result)

CodePudding user response:

You are close, but let's break this down a bit and here's what we're going to do:

  • construct an new object that initially contains an object under the columns keys.
  • get the keys found in the payload object (the left and right keys).
  • loop through the arrays under the found keys (the left and right keys) that contain the field names (name, phone and address).
  • append an object that contains the pinned key where the value depends on the actual position (either left or right).

Here's a live demo to illustrate:

const payload = {
    left: ['name', 'phone'],
    right: ['address']
  },
  // "refined" object will programatically construct an object under the "columns" key
  refined = {
    // get the keys from "payload" object
    columns: Object.keys(payload).reduce((a, c) => {
      // construct an object that has the following structure: "{pinned: '...'}" for every value in the arrays found in the "payload" object
      payload[c].forEach(attr => a[attr] = {
        pinned: c
      });
      return a;
    }, {})
  };

// print the result
console.log(refined);

Learn more about Object.keys() on MDN.

Learn more about Array.prototype.reduce() method on MDN.

  • Related