2

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 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer - I'm trying to not hardcode the column names, and extract them, then use them. Is there any way to extract them from a colNames array in your function? Like colNames = ['Names', 'Nums', 'Range'] ?
@WaveRider edited to handle column names dynamically
Looks good! One change needed: there's one dependency remaining on a column name in your line let length = Object.values(rawPayload["Names"]).length;, which can/should be changed to: const length = Object.values(rawPayload[colNames[0]]).length; ...and then you win the prize ;) ...Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.