Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling.

I'm working with an array of objects that have nested properties which I need to loop through and consolidate.

var items = [{
        name: "flat bread",
        price: "5",
        components: [
            { qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
            { qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
            { qty: 1.5, unit: "g", ingredient: { name: "salt", price: 1.2, perAmount: 1, unit: "kg" } },
            { qty: 28.35, unit: "g", ingredient: { name: "butter", price: "6", perAmount: 500, unit: "g" } }
        ]
    },
    {
        name: "pancake",
        price: "15",
        components: [
            { qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
            { qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
            { qty: 2, unit: "each", ingredient: { name: "egg", price: 5, perAmount: 12, unit: "each" } },
            { qty: 12.5, unit: "g", ingredient: { name: "sugar", price: 2.20, perAmount: 2, unit: "kg" } }
        ]
    },
    {
        name: "crepe",
        price: "10",
        components: [
            { qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
            { qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
            { qty: 2, unit: "each", ingredient: { name: "egg", price: 5, perAmount: 12, unit: "each" } },
            { qty: 28.35, unit: "g", ingredient: { name: "butter", price: "6", perAmount: 500, unit: "g" } }
        ]
    }
];


consolidatedComponents = items.map((item) => {
    return { components: item.components }
});
console.log(consolidatedComponents);

I'm aiming to achieve a result similar to this:

  • 360g flour
  • 750ml milk
  • 1.5g salt 4 eggs
  • 12.5g sugar
  • 56.7g butter

I understand I'll need to convert units later on, assuming they're consistent across all items/ingredients.

Answer №1

If you want to organize all items based on ingredients, consider using an object to store them.

To display a list of the grouped items, you can iterate through the object.

const
    items = [{ name: "flat bread", price: "5", components: [{ qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } }, { qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } }, { qty: 1.5, unit: "g", ingredient: { name: "salt", price: 1.2, perAmount: 1, unit: "kg" } }, { qty: 28.35, unit: "g", ingredient: { name: "butter", price: "6", perAmount: 500, unit: "g" } }] }, { name: "pancake", price: "15", components: [{ qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } }, { qty: 250, unit:...
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

An Array Selection That Fails to Display Results

I am currently working on a CRON job that needs to run daily. The job involves checking a MySql table for a specific date in the 'FAPforSale_repost35' field. If the date matches today's date, the job will proceed to delete photo images from ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

Perform a jQuery function and SQL query when a selection is made in a dropdown menu

Struggling to execute a SQL query on drop-down menu selection. Here's my current code: <script> $('#templateid').change(function(DoUpdateOnSelect) { $.post('page.edit.php?page_id=(-->Need help in retrieving this id from the pa ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

How can I show or hide all child elements of a DOM node using JavaScript?

Assume I have a situation where the HTML below is present and I aim to dynamically conceal all the descendants of the 'overlay' div <div id="overlay" class="foo"> <h2 class="title">title</h2> ...

Querying Firebase by the value of a child node

Here is how my structure looks like: 2017511 UcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 50 value2: 1200 value3: "blabla" AcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 55 value2: 2200 value3: "balabla" BcQefEaHJG6fteGsbsiaWjQ6 ...

The preflight request for OPTIONS is receiving a 400 bad request error on the secure HTTPS

When making an Ajax call on the front end and calling a WCF service through Ajax, I encountered an issue with adding headers. As a result, a preflight OPTIONS request is triggered but fails due to the URL being blocked by CORS policy. I tried adding the f ...

Ways to effectively store continuous scale data in a database

I am currently running a straightforward Node.js server (using Express) on my local machine on port 8000. By utilizing the npm package serialport, I have successfully connected to a scale and am able to retrieve its weight in a continuous manner as shown ...

Outputting a variable using javascript

My challenge is to efficiently print the contract variable, which contains HTML content fetched from the server. How can I achieve this easily? I want the print window in Chrome to display the document with the contents of my variable when I click a button ...

Set checkbox variable to undefined at all times

I am having trouble determining the state (True/False/null, etc.) of my "CSS-only" toggle switch. No matter what I try, I keep getting a null value. I'm not sure why this is happening, but it seems that the checkbox input is not functioning as expecte ...

Determine the location based on the preceding parameter of $routeChangeError using AngularJS

I am currently monitoring events of the type $routeChangeError within a run block in my application. $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { if (!!previous) { console.log(previous); $locati ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

Blockage preventing text entry in a textarea

To enhance the basic formatting capabilities of a textarea, I implemented a solution where a div overlay with the same monospace font and position is used. This approach allows for displaying the text in the div with different colors and boldness. However ...

Issues with Express js routing functionality and executing mysql queries

As I dive into learning Node and Express, I'm encountering issues with routing in Express. I aim to create a well-organized and modular code for handling routes, particularly when querying data from a MySQL database: Let's start with my app.js f ...

Condense dictionaries within a list of dictionaries in Python

I have a set of dictionaries that may vary in size. Each dictionary contains unique keys, but the same key can be found in multiple dictionaries. Values are unique across all dictionaries. My goal is to condense these dictionaries to include only the key- ...

JavaScript - The left dropdown menu stubbornly remains visible when clicked in white space, unlike the right dropdown which disappears as expected. Puzzled by this inconsistency

Whenever I click on the selection criteria box, a dropdown menu appears. Clicking on the white space or the data table button makes the drop-down menu disappear, which is good. However, when I perform the same action for 'choose data table,' the ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

Accessing Private Files with Signed URLs from AWS S3

Issue: The challenge is to securely allow users to upload a file and retrieve it later. The files are stored in private Buckets and objects using S3 pre-signed URLs for uploading. However, fetching the file poses a problem as the signed URLs expire after ...

struggling to transfer information from JavaScript to Jade within the Node.js environment

Currently, I am retrieving a row from a Cassandra table called "emp". My objective is to pass the data retrieved from the JavaScript file to a Jade file in order to display this information on the user interface. In my JavaScript function: router.get(&a ...