tito tito - 3 months ago 17
JSON Question

Display json data in spreadsheet like looking html table using angular

I need help regarding rendering this JSON data in html table using angular:

[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}]


My rendered html table should look like this

Test1 Test2
John 20 50
Doug 10 100


Somehow values need to be grouped by, and then rendered, but to keep matching data. Also that first position in array[0][0] should be empty. Any help will be appreciated.

Answer

So you can group your data by name , and have Object of arrays like following :

{
  "John": [
    {
      "task": "Test1",
      "number": 20,
      "name": "John"
    },
    {
      "task": "Test2",
      "number": 50,
      "name": "John"
    }
  ],
  "Doug": [
    {
      "task": "Test1",
      "number": 10,
      "name": "Doug"
    },
    {
      "task": "Test2",
      "number": 100,
      "name": "Doug"
    }
  ]
}

Then , define a function to retrieve data by name & task : getItemBy=function(name,task)

  • Those two steps will make your algo easy to render HTML table as u want :

DEMO :

var data=[{
  "task": "Test1",
  "number": 20,
  "name": "John"
 }, 
 {
  "task": "Test1",
  "number": 10,
  "name": "Doug"
 }, 
 {
  "task": "Test2",
  "number": 50,
  "name": "John"
 }, 
 {
  "task": "Test2",
  "number": 100,
  "name": "Doug"
}];

 var groupBy=function(arr,key) {
      return arr.reduce(function(rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
};
 //------
var groupedByName=groupBy(data,'name');

var getItemBy=function(name,task){
    return groupedByName[name].filter((item)=>item.task===task)
 };

//------


//--
console.log(`***** Item where name=John & task=Test1`,
   getItemBy('John','Test1')
)
console.log(`****** All data after grouping`,
    groupedByName
)