Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of objects to form data into tabular format

I have following array of objects :

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut",
    "completed": false
  }
]

I want following as output :

userId | id | title       | completed |
  1    | 1  | delectus aut| false     |
  1    | 2  | quis ut     | false     |

I have tried following using lodash , but somehow I feel there us better solution than this, considering the number of loops:

jsonObject = response; // consider the above mention object here.  
keys = _.keys(json[0]); 

Here what I found is that json[0] will not in all case going to be same, so what is the best way to find the solution for this.

Any help will be appreciated!!!

like image 568
imrajshah Avatar asked May 21 '26 10:05

imrajshah


1 Answers

Inspired from @Akrion's solution, here is the modified version.

Little lengthy solution, but this will help you if:

  1. You have different keys in your JSON data
  2. You have different key sequence in the object
  3. Want to set a default value in case data is not available

const json = [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut",
    "completed": true
  },
  {
    "completed": false,
    "userId": 1,
    "title": "quis ut",
    "id": 2,
    "extraProp": "test"
  },
];

const headers = Array.from(new Set(json.reduce((acc, cur) =>
  [...acc, ...Object.keys(cur)], [])));

const data = [headers];
const defaultValue = 'NA';

json.forEach(item => {
  data.push(headers.reduce((acc, header) =>
    acc.push(item.hasOwnProperty(header) ? item[header] : defaultValue) && acc, []));
});
console.log(data);

Stackblitz Link: https://stackblitz.com/edit/js-zyh1ps

like image 184
Purab Avatar answered May 23 '26 14:05

Purab