How does the 'order' stack up against the 'products' array? Display the names of the products that are included in the order

I have an array of items for sale:

const products = {
    {
        id: product1,
        name: 'Product A',
        price: 100
    },
    {
        id: product2,
        name: 'Product B',
        price: 200
    },
    {
        id: product3,
        name: 'Product C',
        price: 150
    }
}

There is also a state representing the current order with quantities of each product. For example, the order contains 1 Product A and 2 Product B:

const orderState = {
    product1: 1,
    product2: 2
}

I am looking to display the name of each product along with the quantity in the order. I am using React but believe plain JavaScript will suffice for this task.

The desired HTML output should resemble:

<ul>
 <li>Product A x1 = $1</li>
 <li>Product B x2 = $4</li>
</ul>

Answer №1

The challenge you are facing appears to be related to how you have structured your data storage. To address this, the first step is to ensure that the array of products is indeed an array:

const products = [
    {
        id: item1,
        name: 'My product',
        price: 100
    }, //...
];

Furthermore, what is the meaning or value of the item1 identifier? Is it a specific ID, perhaps an integer, used to uniquely identify each product?

To manage the "order state", consider creating an object that contains an array of references to the individual products like so:

const orderState = {
    products: [
        {
            productID: item1,
            quantity: 1
        },
        {
            productID: item2,
            quantity: 2
        }
    ]
}

This restructured data model allows for easier manipulation and processing. Depending on the tools at your disposal, such as template engines, there are various methods to generate output. As an illustration, here's a simple logic to construct a string output:

var output = '<ul>';

for (var i = 0; i < orderState.products.length; i++) {

    var product = {};
    for (var j = 0; j < products.length; j++) {
        if (products[j].id == orderState.products[i].id) {
            product = products[j];
            break;
        }
    }

    output += '<li>' + product.name + ' x' + orderState.products[i].quantity + ' = $' + (product.price * orderState.products[i].quantity) + '</li>';
}

output += '</ul>';

As needed, you can refactor and enhance this approach. For instance, consider abstracting out the logic to find a product based on its id into a separate function or utilizing built-in JavaScript functions or frameworks for streamlined operations. Keeping your data structures well-organized simplifies the coding process significantly.

Answer №2

Here is a solution that allows you to retrieve the names of selected products in accordance with your query.

const orderedProductIds = Object.keys(orderState);
let productNames = [];
for (let product of products) {
    if (orderedProductIds.includes(product.id)) {
        productNames.push(product.name);
    }
}
console.log(productNames);

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

In Laravel Blade, I am looking to display a Modal popup and dynamically pass data based on the user's ID

When a user clicks on the "View Details" Button, I need to display a popup modal with information specific to that user. The data for each user is stored in the $user variable. I would like to achieve the same functionality as demonstrated on this website ...

Tips for combining a select option and search field into a seamless integrated feature

I'm looking to implement a search field in my project that includes the ability to select specific parameters before running the search. I want it to have a seamless design similar to the image shown below. https://i.sstatic.net/niWP8.png Although I ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

Fundamentals of Angular 2

It's not just an inconvenience, but something that truly frustrates me. Could someone please clarify the following: Why does Angular load these scripts in HTML directly from node_modules https://i.sstatic.net/D8UrG.png Why am I unable to simply imp ...

Executing a serverless function in Next.js using getStaticPaths: A step-by-step guide

In my current project, I am utilizing Next.js and the Vercel deployment workflow. To set up page generation at build time, I have been following a guide that demonstrates how to generate pages based on an external API's response. // At build time, t ...

What is the best way to showcase all menu and submenu items in separate dropdown lists?

Having trouble with my code, it's not functioning properly. I can't pinpoint the error. The menu displays correctly but the submenu isn't showing up under specific menus. Here is the code snippet: ##Table: menus## id name ...

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

How can we showcase the data within this loop on the user interface in React JS?

I'm currently working with React JS and I have a question regarding how to display data from a loop in the UI. The code snippet below shows the data being logged to the console, but I want to show it on the actual user interface. Could you please guid ...

Send an array using jQuery's $.post method

I am experiencing an issue with sending an array in $.post to PHP. When I use var_dump, the result is showing as "NULL" and JSON.stringify is not working. JQUERY var photobox = []; photobox.push(e.target.result); $.post("../modules/upload.php",{"imag ...

issue with brightcove player's complete event not triggering upon video replay

I have a videoplayer with an event listener added in an onTemplateReady function. Upon completion of the video, I want to replay it: videoPlayer.addEventListener(brightcove.api.events.MediaEvent.COMPLETE, completedCallback); function completedCallback(){ ...

Error: Unable to retrieve current location using 'Geolocation' in React

import "./App.css"; import { useState, useEffect } from "react"; function App() { const [lat, setLat] = useState(null); const [long, setLong] = useState(null); const [data, setData] = useState(null); const [error, setError] = u ...

Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown? var url = "https://fantasy.premierleague.com/ ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Design a recurring report using an endless JavaScript cycle

I am in the process of creating a brand new scheduled report and have encountered an issue. How can I incorporate a script that includes a loop to run a specific function every 10 seconds? Here's what I have so far: var count = 1; while(count > 0 ...

What are some ways I can improve the readability of this if-else function in Javascript ES6?

As a newcomer to React development, I am currently in the process of tidying up my code. One issue that I am facing is how to deal with a particular function while minimizing the use of if-else statements. const calculatePerPage = () => { if ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...