Search code examples
javascriptjsonreactjsreact-data-griddatasheet

Parse list type data into different format to make compatible for spreadsheet


I am new in JavaScript and react If can't explain the problem correctly, please post a comment so at least I can tell more.

Thanks a million in advance will appreciate if anyone can give me a little help

I've been stumped on this for hours and hours I can't figure out a solution to solve this problem.

Say I have data in list type which need to parse from one format to another formate So that I can make compatible with the react-datasheet format to display the spreadsheet

Sample data:

const sampleData = [
  {
    question: "what is your name?",
    answer: "Ben",
    topic: "names"
  },
  {
    question: "what is your name?",
    answer: "Will",
    topic: "names"
  },
  {
    question: "What is your brother's age?",
    answer: 55,
    topic: "ages"
  }
]
Expected results 
 grid: [
        [
          { readOnly: true, value: "SL" },
          { value: "topic", readOnly: true },
          { value: "question", readOnly: true },
          { value: "answer", readOnly: true },
        ],
        [
          { readOnly: true, value: 1 },
          { value: 'names' },
          { value: ' what is your name?' },
          { value: 'Ben' },
        ],
        [
          { readOnly: true, value: 2 },
          { value:'names' },
          { value: 'what is your name?' },
          { value: 'Willi' },
        ],
        [
          { readOnly: true, value: 3 },
          { value: 'ages' },
          { value: "What is your brother's age?" },
          { value: 33 },
        ],
      ]


Solution

  • const sampleData = [
      {
        question: "what is your name?",
        answer: "Ben",
        topic: "names"
      },
      {
        question: "what is your name?",
        answer: "Will",
        topic: "names"
      },
      {
        question: "What is your brother's age?",
        answer: 55,
        topic: "ages"
      }
    ]
    
    // First, for each object in sampleData, construct an array of objects:
    var grid = sampleData.map(function(currentValue, index, a) {
        return [
            { readOnly: true, value: index + 1 },
            { value: currentValue.topic },
            { value: currentValue.question },
            { value: currentValue.answer }
        ];
    });
    
    // Then prepend the "header/config" array of objects:
    grid.unshift([
        { readOnly: true, value: "SL" },
        { value: "topic", readOnly: true },
        { value: "question", readOnly: true },
        { value: "answer", readOnly: true },
    ]);
    
    // Finally, wrap grid in an object:
    var expectedResults = {
        grid: grid
    }
    console.log(expectedResults);