-1

I have this object of array

[
  {
    package_size: 12,
    qty: 24
  },
  {
    package_size: 24,
    qty: 60
  }
]

What I am trying to do:

If I added another object in this array and it has equal value to any of the package_size for example if I want to add package_size: 12 && qty: 50 then the first element in the array become:

[
  {
    package_size: 12,
    qty: 74
  },
  {
    package_size: 24,
    qty: 60
  }
]
Andreas
  • 21,535
  • 7
  • 47
  • 56
Dill
  • 327
  • 2
  • 5
  • 12
  • You can use findIndex on array if you get value greater than or equal to 0 then increment the qty else push that object – Abhay Sehgal Aug 25 '18 at 12:32
  • @AbhaySehgal - Or `find` (*if* that's what the OP's saying they want to do). – T.J. Crowder Aug 25 '18 at 12:33
  • Hi! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) It's not clear what you're asking or what you've already tried, found during your research, etc. Please update the question with a [mcve] of the setup and an example of your attempt to solve the problem. – T.J. Crowder Aug 25 '18 at 12:34
  • That's just a combination of iterating over the elements of an array, reading the value of a property and comparing it against a given value... – Andreas Aug 25 '18 at 12:36
  • 1
    Possible duplicate of [Sum of array object property values in new array of objects in Javascript](https://stackoverflow.com/questions/37481539/sum-of-array-object-property-values-in-new-array-of-objects-in-javascript) – Heretic Monkey Aug 25 '18 at 12:46
  • Okay thank you guys.. I will try to improve my question next time – Dill Aug 25 '18 at 13:19

2 Answers2

0

You can achieve what you want turning the array into a dictionnary and using a reducer

let items = [
  {
    package_size: 12,
    qty: 24
  },
  {
    package_size: 24,
    qty: 60
  },
  {
    package_size: 12,
    qty: 50
  },
];

// Transform the array into a dictionnary
items = items.reduce((acc, item) => {
  const key = item.package_size;
  acc[key] = acc[key] || 0;
  acc[key] += item.qty;
  return acc;
}, Object.create(null));

// Transform dictionnary into an array
const mergedItems = [];
Object.keys(items).forEach((key) => {
  mergedItems.push({
    package_size: key,
    qty: items[key]
  });
});

console.log(mergedItems);
Baboo
  • 4,008
  • 3
  • 18
  • 33
0

As has been mentioned in the comments .find is your friend. You could use a custom add function to add new items to the array.

let items = [
  {
    package_size: 12,
    qty: 24
  },
  {
    package_size: 24,
    qty: 60
  }
];

let addItem = (item) => {
  let slot = items.find(e => e.package_size == item.package_size);
  if (slot) {
    slot.qty += item.qty;
  } else {
    items.push(item);
  }
};

addItem({package_size: 12, qty: 10});
console.log(items);
addItem({package_size: 13, qty: 1});
console.log(items);
James
  • 20,957
  • 5
  • 26
  • 41