0

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.

catzndogz
  • 13
  • 1
  • 4

3 Answers3

1

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)
wardialer
  • 490
  • 3
  • 7
1

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.

ThS
  • 4,597
  • 2
  • 15
  • 27
1

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);
symlink
  • 11,984
  • 7
  • 29
  • 50