Yuva Mac
Yuva Mac

Reputation: 75

Underscore groupBy of nested object elements

I have some data with nested objects need to groupBy nested object using underscoreJS.

[
      {
        "_id": "58e28acba878a54951c84e36",
        "InId": "5809c226e41a193f4ffc1fa5",
        "StuID": "58185aacd7e86244252eb3f0",
        "ExamList": {
          "Type": "FinalMk",
          "SchdlId": "58e28acba878a54951c84dd0",
          "Exams": {
            "SubjId": "5825803ec4a0aff62070d9f5",
            "MaxMark": 100,
            "PassMark": 50,
            "ExDate": "2016-08-11T18:30:00.000Z",
            "Mark": 62
          }
        }
      },
      {
        "_id": "58e28acba878a54951c84e36",
        "InId": "5809c226e41a193f4ffc1fa5",
        "StuID": "58185aacd7e86244252eb3f0",
        "ExamList": {
          "Type": "FinalMk",
          "SchdlId": "58e28acba878a54951c84dd0",
          "Exams": {
            "SubjId": "5825803ec4a0aff62070d9f6",
            "MaxMark": 100,
            "PassMark": 50,
            "ExDate": "2016-08-09T18:30:00.000Z",
            "Mark": 76
          }
        }
      },
    ],
    [
      {
        "_id": "58e28acba878a54951c84e4d",
        "InId": "5809c226e41a193f4ffc1fa5",
        "StuID": "58185aacd7e86244252eb3ec",
        "ExamList": {
          "Type": "FinalMk",
          "SchdlId": "58e28acba878a54951c84dd0",
          "Exams": {
            "SubjId": "5825803ec4a0aff62070d9f5",
            "MaxMark": 100,
            "PassMark": 50,
            "ExDate": "2016-08-11T18:30:00.000Z",
            "Mark": 59
          }
        }
      },
      {
        "_id": "58e28acba878a54951c84e4d",
        "InId": "5809c226e41a193f4ffc1fa5",
        "StuID": "58185aacd7e86244252eb3ec",
        "ExamList": {
          "Type": "FinalMk",
          "SchdlId": "58e28acba878a54951c84dd0",
          "Exams": {
            "SubjId": "5825803ec4a0aff62070d9f6",
            "MaxMark": 100,
            "PassMark": 50,
            "ExDate": "2016-08-09T18:30:00.000Z",
            "Mark": 56
          }
        }
      },
    ],

Here i have to groupBy the nested object using "SubjId"

I have tried with these codes bt ourput is "Exams" of undefined.

var groupBySubj = _.groupBy(docs.ExamList.Exams, 'SubjId');

Upvotes: 0

Views: 605

Answers (1)

qlown
qlown

Reputation: 527

To group by a nested property, you can use a function:

_.groupBy(data, function(student) { return student.ExamList.Exams.SubjId; })

Upvotes: 1

Related Questions