Loop through two sets of data and perform multiplication on specific attributes when they match

I have a unique item that looks like this

Object {SD00002:1,SD00011:3,SD00002:6}

The values of the properties are set automatically. Currently, I have an array of similar objects as shown in the image below: https://i.sstatic.net/pSkvf.jpg

My goal is to loop through these two objects and calculate the total by multiplying the "price" property (found within the objects in the array) with the corresponding value of the properties in the first object. The property of the first object matches the "product code" in the array of objects. I need to multiply all the values with "price" and return the sum of all totals. So far, none of the existing questions on Stack Overflow have addressed my specific issue.

Answer №1

To calculate the total, you can loop through the array and use the value of kodartikulli as the key for the multiplier.

var prices = { SD00002: 1, SD00011: 3, SD00052: 6 },
    items = [
        { price: 189.9, kodartikulli: 'SD00002' },
        { price: 99.9, kodartikulli: 'SD00011' },
        { price: 69.9, kodartikulli: 'SD00052' }
    ],
    totalCost = items.reduce(function (result, item) {
        return result + item.price * (prices[item.kodartikulli] || 0);
    }, 0);

console.log(totalCost); 

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

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

Ways to have a React Component trigger a function with each state update

Using this specific component, the getDisplay function is triggered on every update like normal. When the <div> element is clicked, it becomes hidden: class Example extends React.Component { constructor(props) { super(props); thi ...

Observing nested objects in Vue while utilizing deep watching功能

Is there a way to determine which property change in the object triggered the watch call while watching a data object with multiple properties using deep invocation? data(){ return { user:{ first_name:'', last_na ...

Clicking on a button in HTML to open a JavaScript file

As a beginner in HTML and JavaScript, I am looking for a way to open a JavaScript file when the onclick event of a button in my HTML file is triggered. Can anyone provide me with guidance on how to achieve this? Thank you in advance. ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

mongoose populate method does not return the expected results

My Project Objective I am currently in the process of creating a travel booking platform for a transportation company. One of the key features I am working on is displaying the name of the individual who made the booking on a specific page within the webs ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Testing file uploads with AngularJS unit testsAngularJS unit testing for

Unit tests in AngularJS can easily mock XHR requests using $httpBackend, making it convenient for testing. I recently encountered a situation where I needed to mock XHR for file uploads, but faced some challenges. Take a look at the following code snippe ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Using environment variables in next.config.js allows for successful connection to the database, however, when attempting to use a

Utilizing the serverless-mysql library, I have successfully connected my next app to a remote MySQL DB through an SSH tunnel with the ssh2 library. Although everything is functioning properly, I am looking to enhance the security of my code by removing the ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

Focus automatically on an input component when the value in the Vuex store is updated in Vue

Here's the code snippet from my component: //template <v-select ref='ItemSearchSelect' :options="options"></v-select> ... //script created: function () { this.$store.subscribe((setFocusSearch, state) => { ...

"Discover the power of Node.js and AngularJS for creating clean and user-friendly URLs

Is there a way to configure node/angular so that the index.html/app is displayed at example.com instead of example.com/app/index.html#/home? I attempted placing the index.html at the root of the node server, but the URL remains as example.com/index.html#/ ...

Move the cursor to the bottom of a div that can be edited

I have been struggling to position the cursor at the end of the next or previous editable content tag if the current one is empty. However, when I try to set focus, it always ends up at the beginning of the text instead of the end. I've tried various ...

The positioning of the menu icons varies

When it comes to displaying the search icon in the WordPress toggle bar, I use a custom JavaScript file. This setup is mainly focused on website design and menu functionality. Additionally, I have integrated a newsletter subscription plugin for managing su ...

Issue: [ng:areq] The argument 'HelloController' is not defined as a function, it is displayed as undefined

Struggling to integrate Angular with Django has been quite a challenge for me. After finally managing to make it work, I encountered yet another error. Each time I load the application, the following error message pops up: Error: [ng:areq] Argument ' ...

Resolved issue with sticky header movement after scrolling event

I've been working on a sticky header code, but I'm having trouble achieving a smooth scroll transition. The fixed header seems to jump after just one scroll. Here is the basic HTML structure: <div class="headerWrapper"> <div id="to ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...