Creating an array in React with objects created from two lists

Viewed 66

I'm trying to take a json payload and plot it in a react-table. The required format for their table is (very specific and) the following: (this is the target format I'm trying to create)

  const rTableObj = [
    {'Col1': row1_col1, 'Col2': row1_col2, 'Col3': row1_col3},
    {'Col1': row2_col1, 'Col2': row2_col2, 'Col3': row2_col3},
    ...
  ]

The raw payload object, after the fetch(url) and response.json comes out as:

  rawPayload:
    Names: {0: "Rebecca", 1: "Sally", 2: "Sally", 3: "Charlie", ...}
    Nums: {0: 11, 1: 16, 2: 8, 3: 12, ...}
    Range: {0: 0, 1: 1, 2: 2, 3: 3, ...}

I can extract the column names, such that I'll have (in this example) colNames = ['Names', 'Nums', 'Range'] and I can extract the values to their own object as

  vals: Array(3)
    0: {0: "Rebecca", 1: "Sally", 2: "Sally", 3: "Charlie", ...}
    1: {0: 11, 1: 16, 2: 8, 3: 12, ...}
    2: {0: 0, 1: 1, 2: 2, 3: 3, ...}

But everything I've tried (.map(...), [].concat(_.merge(...), etc.) doesn't get me to the target. I want to be able to send any payload to the mapper such that the properly formatted object is returned. For this example, that would look like this:

  const rTableObj = [
    {'Names': "Rebecca", 'Nums': 11, 'Range': 0},
    {'Names': "Sally", 'Nums': 16, 'Range': 1},
    ...
  ]
1 Answers

Try this: Edited: so it works dynamically with different column names

rawPayload = {
  Names: { 0: "Rebecca", 1: "Sally", 2: "Sally", 3: "Charlie" },
  Nums: { 0: 11, 1: 16, 2: 8, 3: 12 },
  Range: { 0: 0, 1: 1, 2: 2, 3: 3 },
  Age: { 0: 20, 1: 21, 2: 22, 3: 23 }
};

const tableMap = (rawPayload) => {
  let colNames = Object.keys(rawPayload);
  let length = Object.values(rawPayload[colNames[0]]).length

  let rTableObj = [];
  for (let i = 0; i < length; i++) {
    var entry = {};
    for (let j = 0; j < colNames.length; j++) {
      var name = colNames[j];
      entry[name] = rawPayload[name][i];
    }
    rTableObj.push(entry);
  }
  return rTableObj;
};

console.log(tableMap(rawPayload));
Related