Reputation: 187
I have the data in the below format:
[{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'},
{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-2' },
{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-3' },
{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-4' },
{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-5' },
{ Country: 'USA', State: 'CA', City: 'SJ', District: 'SJ-1' },
{ Country: 'USA', State: 'CA', City: 'SJ', District: 'SJ-2' },
{ Country: 'USA', State: 'CA', City: 'SJ', District: 'SJ-3' },
{ Country: 'USA', State: 'CA', City: 'SJ', District: 'SJ-4' } ]
The last two columns i.e Town and Area are optional.
Based, on this data, how can I create a hierarchy? The output expected is like this (I have created this in excel just to show the hierarchy that I need but as array/object)
In conclusion, how can I create a hierarchical data structure?
Any help is appreciated. Thank you.
Upvotes: 1
Views: 614
Reputation: 2290
If you want a hierarchical object you could also try this with plain JS:
const group = (data, fields) => {
return data.reduce((final, dataEntry) => { // iterate dataset lines
let tempObj = final;
fields.forEach((field) => { // iterate fields
const dataField = dataEntry[field];
if (dataField == null) return; // empty field in object
if (!tempObj.hasOwnProperty(dataField)) { // initialize
tempObj[dataField] = {};
}
tempObj = tempObj[dataField];
});
return final;
}, {});
};
const result = group(dataset, ['Country', 'State', 'City', 'District', 'Town', 'Area']);
where dataset
is the initial array you provided
Upvotes: 1
Reputation: 4643
Using lodash to build the hierarchy
let groupBy = (data, attrs) => {
if (!attrs.length) return data
const grouped = _.groupBy(data, attrs[0])
// handles optional attributes
if (grouped['undefined']) {
return grouped['undefined']
}
return _.mapValues(grouped,
values => groupBy(values, attrs.slice(1)))
}
And you can call it like this
groupBy(data, ['Country', 'State', 'City', 'District', 'Town'])
Upvotes: 3