Reputation: 8695
I have an array of objects that I would like to turn into an array (or array-like) object where the keys are the unique values for that given property (something like SQL group by).
var obj = [
{
"ClaimId":"111",
"DrugName":"AMBIEN CR",
"PatientId":1571457415
},
{
"ClaimId":"222",
"DrugName":"AMBIEN CR",
"PatientId":1571457415
},
{
"ClaimId":"333",
"DrugName":"LOTREL",
"PatientId":1571457415
},
{
"ClaimId":"444",
"DrugName":"METHYLPREDNISOLONE",
"PatientId":1571457415
},
{
"ClaimId":"555",
"DrugName":"CYMBALTA",
"PatientId":1513895252
},
{
"ClaimId":"666",
"DrugName":"CYMBALTA",
"PatientId":1513895252
},
{
"ClaimId":"777",
"DrugName":"CYMBALTA",
"PatientId":1513895252
},
{
"ClaimId":"888",
"DrugName":"CYMBALTA",
"PatientId":1513895252
},
{
"ClaimId":"147503879TMQ",
"DrugName":"CYMBALTA",
"PatientId":1513895252
},
{
"ClaimId":"999",
"DrugName":"CYMBALTA",
"PatientId":1513895252
}
]
function splitBy(data, prop) {
var returnObj = {};
var returnArray = [];
$.each(data, function (ix, val) {
if (returnObj[val[prop]] === undefined) {
returnObj[val[prop]] = [];
returnObj[val[prop]].push(val);
}
});
console.log(returnObj);
}
splitBy(obj,'PatientId');
In the fiddle you can see that I get the keys of the array like I want (the two unique values in the PatientId property) but I only get the first value. I understand that's because once the key is no longer undefined, then this check isn't ran, but I couldn't figure out quite how to do it and this is as close as I got. How can I do this with one iteration over this collection?
Upvotes: 4
Views: 669
Reputation: 82267
You almost had it, but you forgot the else clause for once the key existed
if (returnObj[val[prop]] === undefined) {
returnObj[val[prop]] = [];
returnObj[val[prop]].push(val);
}else{
returnObj[val[prop]].push(val);
}
Upvotes: 1
Reputation: 664327
I only get the first value.
That's because you only push the first value - when there had been no key. Change the
if (returnObj[val[prop]] === undefined) {
returnObj[val[prop]] = [];
returnObj[val[prop]].push(val);
}
to
if (returnObj[val[prop]] === undefined) {
returnObj[val[prop]] = [];
}
returnObj[val[prop]].push(val);
Upvotes: 4