Dynamically Generate A 2d Array From Json With Varying Columns
I have a json where I need to organize in the form of 2d array and the number columns are known to be found after the json iteration and they are to be numbered #1 #2 for multiple
Solution 1:
Consider
functionflatten(obj, res = {}, key = '') {
letadd = (d, s) => key ? key + d + s : s;
if (Array.isArray(obj))
obj.forEach((v, n) =>flatten(v, res, add(' #', n + 1)))
elseif (typeof obj === 'object')
Object.entries(obj).forEach(([k, v]) =>flatten(v, res, add(': ', k)))
else
res[key] = obj
return res
}
applied to your data
let flats = crowds.map(obj =>flatten(obj))
console.log(flats)
this would return a list of "flattened" objects like this:
[
{
'name #1: firstName': 'John',
'name #1: middleName': 'Joseph',
'name #1: lastName': 'Briggs',
'addresses #1: type': 'home',
...etc
},
{
'name #1: firstName': 'Bill',
'name #1: lastName': 'Thatcher',
'addresses #1: type': 'home',
...etc
}
]
Now you'll have to build a union of all keys in all flattened objects:
functioncombineKeys(objs) {
let keys = objs.reduce((k, obj) => k.concat(Object.keys(obj)), [])
return [...newSet(keys)]
}
let keys = combineKeys(flats)
and finally make a table from the list of keys:
let table = flats.map(f => keys.map(k => f[k] ?? ''))
Post a Comment for "Dynamically Generate A 2d Array From Json With Varying Columns"