1

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) enter image description here

In conclusion, how can I create a hierarchical data structure?

Any help is appreciated. Thank you.

the_new_guy
  • 147
  • 1
  • 5
  • 17
  • Please learn [the difference between JSON and the Object Literal Notation](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). – str Dec 10 '20 at 08:19

2 Answers2

3

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'])
Rami Jarrar
  • 4,523
  • 7
  • 36
  • 52
  • Thanks. Its working but the output I'm getting is repeating based on what I pass in the attributes like Country,State,CIty,District and town. – the_new_guy Dec 10 '20 at 11:11
1

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

mitsos1os
  • 2,170
  • 1
  • 20
  • 34