Create an object with a normalized structure

0

I have a service that returns an object like this:

[
{id: 1, name: 'Pedro', city:1, state: 1, country: 1},
{id: 2, name: 'Juan', city:12, state: 2, country: 1},
{id: 3, name: 'Ana', city:10, state: 5, country: 1},
{id: 4, name: 'Diego', city:7, state: 9, country: 1},
{id: 5, name: 'Jose', city:4, state: 2, country: 1},
{id: 6, name: 'David', city:7, state: 9, country: 1},
{id: 7, name: 'Adriana', city:1, state: 1, country: 1},
{id: 8, name: 'Jorge', city:15, state: 2, country: 1},
];

How to create an object that has the following structure:

countries >> states >> cities >> persons
    
asked by Kay Plata 08.06.2017 в 22:41
source

1 answer

1

You can run the following code that uses a recursive implementation groupBy using the library Lodash .

_.groupByMulti = function (obj, values, context) {
        if (!values.length)
            return obj;
        var byFirst = _.groupBy(obj, values[0], context),
            rest = values.slice(1);
        for (var prop in byFirst) {
            byFirst[prop] = _.groupByMulti(byFirst[prop], rest, context);
        }
        return byFirst;
    };

    var groupedData = _.groupByMulti(getData(), ['country', 'state', 'city', 'name']);
    console.log(JSON.stringify(groupedData, null, 4));


    function getData() {
        return [
          {id: 1, name: 'Pedro', city:1, state: 1, country: 1},
          {id: 2, name: 'Juan', city:12, state: 2, country: 1},
          {id: 3, name: 'Ana', city:10, state: 5, country: 1},
          {id: 4, name: 'Diego', city:7, state: 9, country: 1},
          {id: 5, name: 'Jose', city:4, state: 2, country: 1},
          {id: 6, name: 'David', city:7, state: 9, country: 1},
          {id: 7, name: 'Adriana', city:1, state: 1, country: 1},
          {id: 8, name: 'Jorge', city:15, state: 2, country: 1},
          ];
    }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
    
answered by 08.06.2017 в 23:14