0

I have my data as following:

{
    meta: {
              format: "csv",
              info: "desc",
              columns: [
              {
                  id: "Name",
                  type: "Text",
                  length: 32          
              }, 
              {
                  id: "Text",
                  type: "Text",
                  length: 128
              }]
          },
    rows: [
              ["John","xxxx"],
              ["Alpha","yyyy"],
              ["Beta","wwww"],
              ["Gamma","zzzz"]]
}

Now, I am struggling to map the records to a Table control as Columns and Rows. Column seems straight forward, straight map, but the rows since lacks a mapping to column I wonder what could be the simplest way.

Approach Steps:

  1. Make a keys[] from column.id of each columns record.
  2. Traverse the rows[]
  3. Each loop, while keys.length create an object as {keys[j]:row[k]}
  4. Push to an array
  5. Recreate the original JSON but replace Rows arrays with Objects

I am really struggling to translate this into code specially at the rows[] parsing and creating Objects. Is there, I am sure there must be, an efficient way to achieve this.

1 Answer 1

1

Here is what you could do. using Array.map and forEach.

var input = {
  meta: {
    format: "csv",
    info: "desc",
    columns: [{
      id: "Name",
      type: "Text",
      length: 32
    }, {
      id: "Text",
      type: "Text",
      length: 128
    }]
  },
  rows: [
    ["John", "xxxx"],
    ["Alpha", "yyyy"],
    ["Beta", "wwww"],
    ["Gamma", "zzzz"]
  ]
};


var columns = input.meta.columns.map((column) => {
  return column.id
});


var rows = input.rows.map((row) => {
  var obj = {};
  row.forEach((column, idx) => {
    obj[columns[idx]] = column;
  });
  return obj;
});

input.rows = rows;
console.log(input);

Sign up to request clarification or add additional context in comments.

2 Comments

many thanks for the reply. This solution works absolutely bang on to get the desired result. Although, my question was a little more towards wondering if there is any smart way of doing the same in SAPUI5 data binding for Table without the need of pre-processing the data. But if thats not possible I'll mark this as the right answer.
I m no expert on sapui5 at all. I wont be able to answer, if there is a better way to do it in SAPUI. However, in general, you need to have a transformer in place to convert from one structure to another. It could either be at server / client.

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.