Four_lo
Four_lo

Reputation: 1150

Group Array into a more complex Array

  1. I create an array of Objects from a database query and call the array jobListRecords. There are multiple records in the array created that have the same "customerID" and "name".
  2. I would like to create a new array that has one record for each customer with a new field , "jobArray", that contains another array of all of that customers services. (see sortCustomer array down below)

An example of the initial array:

jobListRecords = [
    { 
    "customerID" : "1",
    "name" : "Larry Bird",
    "serviceID" : "101",
    "serviceName" : "Dog Walking"
    },
    {
    "customerID" : "2",
    "name" : "Andrew Luck",
    "serviceID" : "202",
    "serviceName" : "Baby Sitting"
    },
    {
    "customerID" : "2",
    "name" : "Andrew Luck",
    "serviceID" : "101",
    "serviceName" : "Dog Walking"
    }
]

Desired Result

sortCustomer Example:

sortCustomer = [
   {
   "customerID" : "1",
   "name" : " Larry Bird",
   "jobArray" : [
           {
           "serviceID" : "101",
           "serviceName" : "Dog Walking"
           }
        ]
    },
    {
    "customerID" : "2",
    "name" : "Andrew Luck",
    "jobArray" : [
            {
            "serviceID" : "202",
            "serviceName" : "Baby Sitting"
            },
            {
           "serviceID" : "101",
            "serviceName" : "Dog Walking"
            }
        ]
    }

Is their a simple or efficient way of solving this without having to iterate through all the data 3+ times. Thank You for your time, below is one of the several things I tried.

I tried solving this using one example I found but it grouped all the serviceIDs together which is not what I need.

Example that DID NOT work that I tried.

jobListGrouped = _
    .chain(jobListRecords)
    .groupBy('customerID')
    .map(function(value, key) {
        return {
            CustomerID: key,
            services: _.pluck(value, 'serviceID')
        }
    })
    .value();

Upvotes: 1

Views: 33

Answers (1)

Bergi
Bergi

Reputation: 664297

You're plucking only the serviceIDs into that array. Instead, you would need to do something like

.map(function(values, key) {
    return {
        customerID: key,
        name: values[0].name.
        services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
    }
})

or even more explicit

.map(function(values, key) {
    return _.extend(_.omit(values[0], 'serviceID', 'serviceName'), {
        services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
    }
})

(where that partial call is the same as function(value) { return _.pick(value, 'serviceID', 'serviceName'); })

Upvotes: 1

Related Questions