Home > database >  Get quantity in object respective with the category
Get quantity in object respective with the category

Time:10-20

I want the result to sum all the quantity of same cat.

    var  data = [
         { cat: 'EK-1',name:"test",info:"mat", quantity: 3},
         { cat: 'EK-2', name:"test2",info:"nat"quantity: 1}
          ];

I have array of object having some similar objects. How to add quantity and create unique object? This is what I tried.

var data = [{
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-2',
    name: "test2",
    info: "nat",
    quantity: 1
  }
];

const products = Array.from(data.reduce((acc, {
    cat,
    quantity
  }) =>
  acc.set(cat, (acc.get(cat) || 0)   quantity),
  new Map()
), ([cat, quantity]) => ({
  cat,
  quantitya
}));

console.log(products);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You first group and sum quantities under categories keys, using reduce and then you discard those keys with Object.values.

 var data = [{
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-2',
        name: "test2",
        info: "nat",
        quantity: 1
    }];


const result = Object.values(data.reduce((acc, item) => {
  if (!acc[item.cat]) {
    acc[item.cat] = item;
  } else {
    acc[item.cat] = { ...item, quantity: item.quantity   acc[item.cat].quantity }
  }
  return acc;      
}, {}))
        

console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could get the complete object as value for the map and increment quantity.

const
    data = [{ cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-2', name: "test2", info: "nat", quantity: 1 }],
    products = Array.from(
          data
              .reduce(
                  (acc, o) => acc.set(o.cat, { ...o, quantity: (acc.get(o.cat)?.quantity || 0)   o.quantity }),
                  new Map
              )
              .values()
    );

console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related