Gastello Gastello - 1 month ago 10
Javascript Question

Group array of objects by several properties with underscore

I have array of objects like this. And they have duplicated property

contactName
and
categoryName
values

[
{
categoryId:1
categoryName:"Default"
contactName:"Anonymous"
name:"Mobile"
value:"+4417087654"
},
{
categoryId:1
categoryName:"Default"
contactName:"Anonymous"
name:"Email"
value:"test2@gmail.com"
},
{
categoryId:1
categoryName:"Default"
contactName:"Test"
name:"Email"
value:"ivdtest@test.com"
},
{
categoryId:1
categoryName:"Default"
contactName:"Test"
name:"Mobile"
value:"+4417087654"
},
{
categoryId:2
categoryName:"Personal"
contactName:"Anonymous"
name:"Email"
value:"ivdtest@test.com"
},
{
categoryId:2
categoryName:"Personal"
contactName:"Anonymous"
name:"Email"
value:"ivdtest@test.com"
},
{
categoryId:2
categoryName:"Personal"
contactName:"Test"
name:"Email"
value:"ivdtest@test.com"
},
{
categoryId:2
categoryName:"Personal"
contactName:"Test"
name:"Email"
value:"ivdtest2@test.com"
}
]


I want to group them by the values of properties
contactName
and
categoryName


It could be something like this

[
{
"categoryId": 1,
"categoryName": "Default",
entity: [
{
"contactName": "Anonymous",
"addresses": [
{
"name": "Mobile",
"value": "+4417087654"
},
{
"name": "Email",
"value": "test2@gmail.com"
},
{
"name": "Email",
"value": "ivdtest@test.com"
}
]
},
{
"contactName": "Test",
"addresses": [
{
"name": "Mobile",
"value": "+4417087654"
},
{
"name": "Email",
"value": "test2@gmail.com"
},
{
"name": "Email",
"value": "ivdtest@test.com"
}
]
}]

},
{
"categoryId": 2,
"categoryName": "Personal",
entity: [
{
"contactName": "Anonymous",
"addresses": [
{
"name": "Mobile",
"value": "+4417087654"
},
{
"name": "Email",
"value": "test2@gmail.com"
},
{
"name": "Email",
"value": "ivdtest@test.com"
}
]
},
{
"contactName": "Test",
"addresses": [
{
"name": "Mobile",
"value": "+4417087654"
},
{
"name": "Email",
"value": "test2@gmail.com"
},
{
"name": "Email",
"value": "ivdtest@test.com"
}
]
}]

}

]

Answer
var output = _.groupBy(input, function(entry) { 
  return entry.categoryName + ',' + entry.contactName; 
});

https://jsfiddle.net/9ttg1t3z/