s sharma s sharma - 5 months ago 11
Javascript Question

Sum value based on distinct unit in array of objects

I am stuck on situation, where I have JSON response like

[{
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 acs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 acs",
"period": "all",
"in": "Evening"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 cs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 cs",
"period": "all",
"in": "Evening"
}];


So, I want to get
dose
key which has
quantity + unit
but response using jQuery I want to get result
e.g. - 3 Acs , 3 cs.

Answer

You can use Array#forEach to iterate over array of objects and create and object to store result.

// An object to store the result
var result = {};

// Iterate over array of objects
arr.forEach(function(obj) {
    // Extract quantity & unit
    var quantity = parseInt(obj.dose.match(/\d+/)[0], 10),
        unit = obj.dose.replace(/\d+/, '').trim();

    // If the unit already exists in the result object
    //    Add the quantity to it
    // else
    //    Store the quantity
    result[unit] = result[unit] ? result[unit] + quantity : quantity;
});

var arr = [{
    "product": "CLINISod",
    "potentiation": "BIOLOGICALLY ACTIVE",
    "dose": "2 acs",
    "period": "all",
    "in": "Morning"
}, {
    "product": "CLINISod",
    "potentiation": "BIOLOGICALLY ACTIVE",
    "dose": "1 acs",
    "period": "all",
    "in": "Evening"
}, {
    "product": "CLINISod",
    "potentiation": "BIOLOGICALLY ACTIVE",
    "dose": "2 cs",
    "period": "all",
    "in": "Morning"
}, {
    "product": "CLINISod",
    "potentiation": "BIOLOGICALLY ACTIVE",
    "dose": "1 cs",
    "period": "all",
    "in": "Evening"
}];

var result = {};
arr.forEach(function(obj) {
    var quantity = parseInt(obj.dose.match(/\d+/)[0], 10),
        unit = obj.dose.replace(/\d+/, '').trim();
    result[unit] = result[unit] ? result[unit] + quantity : quantity;
});

console.log(result);

Comments