Convert key, values JSON array to tabular JSON format

Viewed 121

I have following JSON data for Chart

var chartJson = [
    {
        header : '2016',
        values : [1, 5, 9]
    },
    {
        header : '2017',
        values : [2, 4, 8]
    },
    {
        header : '2018',
        values : [3, 1, 5]
    }
];

And needs to convert it into this format to feed my HTML table

var tableJson = [
    {
        2016 : 1,
        2017 : 2,
        2018 : 3
    },
    {
        2016 : 5,
        2017 : 4,
        2018 : 1
    },
    {
        2016 : 9,
        2017 : 8,
        2018 : 5
    }
];

Any quick help will be appreciated to convert it into this format. I tried using this code, but somehow missing on the logic.

let table = [];
    for(var row of chartJson ){
        for(var value of row.values)
        {
            table.push(
                {
                    column : row.header,
                    value : value
                });
        }
    }
3 Answers

var chartJson = [{
    header: '2016',
    values: [1, 5, 9]
  },
  {
    header: '2017',
    values: [2, 4, 8]
  },
  {
    header: '2018',
    values: [3, 1, 5]
  }
];

let table = [];
chartJson.forEach((row, index) => {
  row.values.forEach((val, j) => {
    table[j] = { ...table[j],
      [row.header]: val
    }
  });
});

console.log(table)

  1. Iterate through every chartJson's element with its' values(through inner loop) till values' length and make an object from that.
  2. Finally, push that object into the table array.

That's it.

Have a look at the snippet below:

var chartJson = [
    {
        header: '2016',
        values: [1, 5, 9]
    },
    {
        header: '2017',
        values: [2, 4, 8]
    },
    {
        header: '2018',
        values: [3, 1, 5]
    }
];

let table = [];
let len_of_chartJson = chartJson.length, len_of_values = chartJson[0].values.length;

for (var i = 0; i < len_of_chartJson; i++) {
    let obj = {};
    for (var j = 0; j < len_of_values; j++) {
        obj[chartJson[j].header] = chartJson[j].values[i];
    }
    table.push(obj);
}

console.log(table);

let table = chartJson.reduce((tbl, rec) => {
          rec.values.forEach((num, index) => {
                  if(!tbl[index]){
                          tbl[index] = {}
                  }
                  tbl[index][rec.header] = num
          })
          return tbl
          }, [])

Array reduce function is used to loop through each object, than for each object it loop through each value, checking if the index exist in the table, if it does not exist, it create an empty object at current index. Finally it creates a key value in the current index object.

You read more about reduce function below https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Related