Skip to content
Advertisement

How to breakdown an array of objects?

I have an array of objects and i need to classify each object by name and then get the addition of some properties.

To be more specific, I have a cart with some orders and i need to breakdown by product name so i can calculate how many items of that product were bought.

JavaScript

That is the dummy data,

I mapped the orders array and then mapped the products array, then i used .flat() method to get another array of objects but simplified.

Now I am stuck.

JavaScript

This is the result:

JavaScript

At this point, i need to know how many apples, Coconut, Garlic were sold.

Example: name: ‘Apple’, unit: ‘X6 und’, qty: 6 name: ‘Apple’, unit: ‘X12 und’, qty: 1 name: ‘Lemon’, unit: ‘500gr’, qty: 9 an so on…

Any clue? I am completely lost 🙁

Advertisement

Answer

Probably not as elegant as reduce, but kind of fun, is the following: Starting with your original orders (no need for the intermediate step, unless you want it), initiate an empty array, like ordersArray = [], and run the following:

JavaScript

Your result is:

JavaScript

This looks right (I’m not sure where the { name: 'Apple', unit: 'x12 und', qty: 2 } object came from for your intermediate step 🙂 ). Lately, I’ve been storing this kind of information in an object (see here). It would be very similar, with only slight differences: Start with the same orders (obviously), and then define an empty object ordersObject = {}.

JavaScript

The result is similar, but easier to update, retrieve data, etc.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement