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.

1

2 Answers 2

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'])
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.