Home > database >  I am looking for a solution to group objects by a unique key together
I am looking for a solution to group objects by a unique key together

Time:02-11

I currently have an array something like this, there is a unique key in each object I can use (example: "_key": "qpfPdAZdFk"), I want to be able to group them into their own arrays

[
 {
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    1:1

},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    2:2
},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    }
    3:3
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    4:4

},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    5:5
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    6:6
},
]

I want to be able return a grouped together array's like this

[
[
    {
        "node": {
            "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        1:1

    },
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        }
        3:3
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        4:4

    },
],

[
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        2:2
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        5:5
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        6:6
    },
 ]
]

I have been trying to think of a solution but I cant seem to get it working, is there some kind of way in JavaScript to identify by unique? I can use Lodash if that would work.

Any help much appreciated

CodePudding user response:

Lodash is prefect for situations like this. Lodash has a groupBy function https://lodash.com/docs/4.17.15#groupBy which you can use like this

import _ from 'lodash'

const groupedCollection = _.groupBy(collection, 'node._key')
  • Related