Home > OS >  How to sum up the values of one key in an array of objects using Javascript?
How to sum up the values of one key in an array of objects using Javascript?

Time:02-02

I have the following array of objects:

[
  {
    id: "02787783",
    name: "Sedariston Konzentrat Hartkapseln",
    price: 15.69,
    quantity: 2,
    category: "beruhigung-schlaf,ruhe-schlaf,unruhe-verstimmung,x-joh"  
              "anniskraut-kapseln,nerven-beruhigung-schlaf,stress-bur"  
              "n-out"
  },
  {
    id: "16705004",
    name: "Diclox forte Schmerzgel 20 mg/g",
    price: 8.32,
    quantity: 1,
    category: "ratiopharm-gelenke-venen,verstauchungen-prellungen,sch"  
              "merzmittel"
  }
]

And I would like to obtain a single object containing a generic id, the sum of the price*quantity, and a static quantity of 1. So for the example above, the expected is:

{
    "id": "totalAmount",
    "price": 39.7,
    "quantity": 1
}

This is the code I have, which is working correctly, but is quite inefficient if you ask me, as I believe it could be done in one step, probably using the reduce method, but not sure:

function(){
  var itemsIntermediate = [];
  var items = [];
  var checkoutProducts = [
  {
    id: "02787783",
    name: "Sedariston Konzentrat Hartkapseln",
    price: 15.69,
    quantity: 2,
    category: "beruhigung-schlaf,ruhe-schlaf,unruhe-verstimmung,x-joh"  
              "anniskraut-kapseln,nerven-beruhigung-schlaf,stress-bur"  
              "n-out"
  },
  {
    id: "16705004",
    name: "Diclox forte Schmerzgel 20 mg/g",
    price: 8.32,
    quantity: 1,
    category: "ratiopharm-gelenke-venen,verstauchungen-prellungen,sch"  
              "merzmittel"
  }
];

  itemsIntermediate = checkoutProducts.slice().map(function(product){
      return {
        id: "totalAmount",
          price: parseFloat(product.price)*product.quantity
      };
    });

  var holder = {};

  itemsIntermediate.forEach(function(d) {
    if (holder.hasOwnProperty(d.id)) {
      holder[d.id] = holder[d.id]   d.price;
    } else {
      holder[d.id] = d.price;
    }
  });

  for (var prop in holder) {
    items.push({ id: prop, price: holder[prop], quantity: 1 });
  }

  return items;
}

Any ideas on how to make it more efficient?

CodePudding user response:

You could get the total first and then build an object.

const
    data = [{ id: "02787783", name: "Sedariston Konzentrat Hartkapseln", price: 15.69, quantity: 2, category: "beruhigung-schlaf,ruhe-schlaf,unruhe-verstimmung,x-johanniskraut-kapseln,nerven-beruhigung-schlaf,stress-burn-out" }, { id: "16705004", name: "Diclox forte Schmerzgel 20 mg/g", price: 8.32, quantity: 1, category: "ratiopharm-gelenke-venen,verstauchungen-prellungen,schmerzmittel" }],
    price = data.reduce(
        (total, { price, quantity }) => total   price * quantity,
        0
    ),
    result = { id: "totalAmount", price, quantity: 1 };

console.log(result);

CodePudding user response:

You can use Array#reduce with an object as the accumulator like so:

let arr=[{id:"02787783",name:"Sedariston Konzentrat Hartkapseln",price:15.69,quantity:2,category:"beruhigung-schlaf,ruhe-schlaf,unruhe-verstimmung,x-johanniskraut-kapseln,nerven-beruhigung-schlaf,stress-burn-out"},{id:"16705004",name:"Diclox forte Schmerzgel 20 mg/g",price:8.32,quantity:1,category:"ratiopharm-gelenke-venen,verstauchungen-prellungen,schmerzmittel"}];
let res = arr.reduce((acc, {price, quantity}) => (acc.price  = price * quantity, acc), 
  {id: 'totalAmount', price: 0, quantity: 1});
console.log(res);

CodePudding user response:

I would use reduce, as you said.

let obj = [
  {
    id: "02787783",
    name: "Sedariston Konzentrat Hartkapseln",
    price: 15.69,
    quantity: 2,
    category:
      "beruhigung-schlaf,ruhe-schlaf,unruhe-verstimmung,x-joh"  
      "anniskraut-kapseln,nerven-beruhigung-schlaf,stress-bur"  
      "n-out",
  },
  {
    id: "16705004",
    name: "Diclox forte Schmerzgel 20 mg/g",
    price: 8.32,
    quantity: 1,
    category:
      "ratiopharm-gelenke-venen,verstauchungen-prellungen,sch"   "merzmittel",
  },
];

const result = obj.reduce(
  (acc, cur) => {
    acc.price  = cur.price * cur.quantity;
    return acc;
  },
  {
    id: "totalAmount",
    price: 0,
    quantity: 1,
  }
);

console.log(result);

  • Related