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!!!
Inspired from @Akrion's solution, here is the modified version.
Little lengthy solution, but this will help you if:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With