Mahajan344 Mahajan344 - 5 months ago 11
Javascript Question

foreach array to create new array with nested array

I have array in javascript

var companyArr = [{
entityName : "ABC Company, LLC",
appointmentName : "ABCware",
eventName: " Annual Report",
dueDate : " 2017-03-01"
},{
entityName : "ABC Company, LLC",
appointmentName : "ABCware",
eventName: " Business Licence Renewal",
dueDate : " 2017-06-01"
},{
entityName : "XYZ Companies, LLC",
appointmentName: "XYZWare",
eventName : " Annual Report - II",
dueDate : " 2016-06-27"
}]


Now I have to groupby this array on field
entityName
and
appointmentName
to make output like this

var newCompanyArr = [{
entityName : "ABC Company, LLC",
appointmentName : "ABCware",
eventArray : [
{ eventName : " Annual Report",
dueDate : " 2017-03-01"
},
{ eventName :" Business Licence Renewal",
dueDate : " 2017-06-01"
}
]
},
{
entityName : "XYZ Companies, LLC",
appointmentName: "XYZWare",
eventArray : [
{eventName :" Annual Report - II",
dueDate : " 2016-06-27"
}
]
}]

Answer

You could use the smart Array#forEach with an object for referencing the group.

var companyArr = [{ entityName: "ABC Company, LLC", appointmentName: "ABCware", eventName: "Annual Report", dueDate: "2017-03-01" }, { entityName: "ABC Company, LLC", appointmentName: "ABCware", eventName: "Business Licence Renewal", dueDate: "2017-06-01" }, { entityName: "XYZ Companies, LLC", appointmentName: "XYZWare", eventName: "Annual Report - II", dueDate: "2016-06-27" }],
    newCompanyArr = [];

companyArr.forEach(function (a) {
    var key = a.entityName + '|' + a.appointmentName;
    if (!this[key]) {
        this[key] = { entityName: a.entityName, appointmentName: a.appointmentName, eventArray: [] };
        newCompanyArr.push(this[key]);
    }
    this[key].eventArray.push({ eventName: a.eventName, dueDate: a.dueDate });
}, Object.create(null));

console.log(newCompanyArr);

Comments