Search code examples
javascriptreduxreact-reduxjsonschemanormalizr

normalizr -How to use for grouping based on a property


I need to restructure the data from server API to use in my client application and I came to know about normalizr. I am trying to use this library if possible.

The structure of the data is as follows.

{
    "history": [{
            "_id": "5a09d7a48134664b58eb9ff7",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d79c8134664b58eb9ff6",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d7968134664b58eb9ff5",
            "created": "2017-11-13"
        }, {
            "_id": "5a0349da81069a3754ac1a91",
            "created": "2017-11-08"
        }
    ]
}

I want to group this based on 'created', as follows.

{
    "history": {
        "2017-11-13": [{
                "_id": "5a09d7a48134664b58eb9ff7",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d79c8134664b58eb9ff6",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d7968134664b58eb9ff5",
                "created": "2017-11-13"
            }

        ],
        "2017-11-08": [{
                "_id": "5a0349da81069a3754ac1a91",
                "created": "2017-11-08"
            }
        ]
    }
}

How to do this with normalizr? I know what I need is just restructuring of the data, is normalizr the best option for this?


Solution

  • You could use ES6 version to accomplish this by the following function

    function grouping (arr, key) {
     return (arr || []).reduce((acc, x = {}) => ({
      ...acc,
       [x[key]]: [...acc[x[key]] || [], x]
     }), {})
    }
    

    which takes two parameters, array and the key for grouping by

    function grouping (arr, key) {
      return (arr || []).reduce((acc, x = {}) => ({
        ...acc,
        [x[key]]: [...acc[x[key]] || [], x]
      }), {})
    }
    
    let history = [{
                "_id": "5a09d7a48134664b58eb9ff7",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d79c8134664b58eb9ff6",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d7968134664b58eb9ff5",
                "created": "2017-11-13"
            }, {
                "_id": "5a0349da81069a3754ac1a91",
                "created": "2017-11-08"
            }
        ];
    console.log(grouping(history,'created'));