Adding the values in a column of an array in JavaScript only if they are an exact match

Hey everyone, I've been working on a system where I'm adding products to a cart and saving the selected items in sessionStorage. Here is the JSON data structure that I have saved:

[
  {
    "product": {
      "ref": "42101",
      "price": 390,
      "image": "https://via.placeholder.com/200x200"
    },
    "combinations": [
      {
        "type": "REVAS",
        "option": "REVVNL"
      },
      {
        "type": "CORAS",
        "option": "VNL132"
      },
      {
        "type": "APCAB",
        "option": "VNL132"
      }
    ],
    "amount": 1
  },
  {
    "product": {
      "ref": "42101",
      "price": 390,
      "image": "https://via.placeholder.com/200x200"
    },
    "combinations": [
      {
        "type": "REVAS",
        "option": "REVVNL"
      },
      {
        "type": "CORAS",
        "option": "VNL132"
      },
      {
        "type": "APCAB",
        "option": "VNL132"
      }
    ],
    "amount": 5
  }
]

Everything in this JSON data remains constant except for the 'amount' key, which varies. Is there a way to check if the objects are identical and then sum up the 'amount' values?

Answer №1

After breaking down the problem into manageable parts, I have begun grouping and calculating the sum. To ensure accuracy, I want to iterate through the combinations and create separate objects for different combinations. Is this achievable?

let budgetMap = [{
    product: '',
    combinations: '',
    amount: 0,
}];

let reverseMap = [];

for (var [key, value] of Object.entries(budget)) {
    if (typeof reverseMap[value.product.ref] !== 'undefined') {
        key = reverseMap[value.product.ref];
    } else {
        reverseMap[value.product.ref] = key;
    }

    budgetMap[key].product = value.product;
    budgetMap[key].combinations = value.combinations;
    budgetMap[key].amount += value.amount;
}

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

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Execute the task from an external JavaScript file using npm

Utilizing node and npm as a task runner from gitbash cli has been successful for the most part. However, I am facing an issue where I am unable to call tasks in separate .js files from my package.json. Any assistance with the syntax would be greatly apprec ...

Generating arrays of arrays from a string

Hello everyone, I am currently learning and trying to figure out how to convert a string into an array. var myString = 'one,two\nthree,four\nfive\nsix,seven' What I aim to achieve is converting the string into an array of arrays ...

Reverse the order in which the array is iterated

In the loop below, I am iterating over counts: for (var key in counts) { var entry = counts[key]; for (var entryKey in entry) { arrOfCounts.push(entry[entryKey]); } } I wanted to iterate over counts in reverse order, so I attempte ...

What is the correct way to encode a string of 'numbers' in an array with a letter cipher?

Let's cut to the chase. This task should be simple, but it's giving me a headache. I'm currently working on a secure local network where I need to encrypt an input (specifically an IP address) before securely storing it in a database. I wan ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...

Warning: The name index is not defined in the PHP foreach loop

I'm encountering an issue with retrieving data from two arrays stored in a single variable using a for-each loop. The problem lies with the name index, which is causing an error. Take a look at the code snippet below for reference. Array Array ( ...

How can I accommodate pushState routes from Backbone.js on a node.js express server?

pushState feature was added to Backbone.js in version 0.5. According to the backbone documentation: When using real URLs, your web server must be capable of rendering those pages as well. For example, if you have a route like /documents/100, your web s ...

Modify a variety of CSS styles based on boolean values

I am currently working on a web page that needs to adapt based on the local time of the user. Depending on whether it's morning, afternoon, or evening, I want the background image and color scheme to change accordingly. I have made some progress using ...

Eliminate the deeply embedded stdClass Object within a standalone stdClass Object

I am facing an issue where I need to eliminate nested stdClass Objects. Currently, the output is in the format of: Array ( [0] => Array ( [0] => stdClass Object ( [cs_id] => 1 [cs_service_na ...

To what extent can we anticipate the behavior of the event loop in Node.JS?

When dealing with simple client-side JavaScript code like this example, the behavior of setTimeout is based on the time interval specified (in this case, 0ms), which determines when the JS runtime adds it to the queue as explained here. In Node.JS, things ...

Issue with fetching access token from Azure /oauth2/token endpoint using jQuery, Ajax, or AngularJS due to cross-origin restrictions

I am attempting to obtain an access_token from Azure. Error Message: Unable to fetch : No 'Access-Control-Allow-Origin' header is found on the requested resource. Origin 'http://localhost:61697' cannot access it. Code snippet: fun ...

Acquire the HTML content with a simple click

Is there a method to emphasize the current HTML element when a user hovers their mouse over it (not just one object, but anything on the page) and then copy the content of that particular element when clicked? Are there any JavaScript techniques or librar ...

Encountering an error with my electron application built using create-react-app

While I'm working on my project, my electron window is showing this error message. TypeError: fs.existsSync is not a function getElectronPath ../node_modules/electron/index.js:7 4 | var pathFile = path.join(__dirname, 'path.txt') 5 | ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Encountering a TypeError with state variable in REACTJS

I'm attempting to retrieve array data from a web service API (using JSON) and iterate through the response, but I encounter an error when trying to access the state data in render() using console.log(): Error: TypeError - this.state.jsonStr is unde ...

How can I create an animation effect for a single character using JavaScript or jQuery when hovering over it?

When I try to animate the entire word or any other selector, it works fine. However, when using "blast" as the class, I am unable to animate single characters. //I utilized blast.js to separate each character $("h1").blast({ delimiter: "character" }); ...

What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it? useEffect(() => { updateUs ...

Finding distinct values in a multi-dimensional array using PHP

Similar Question: php multi-dimensional array remove duplicate I am facing a challenge with an array structure like this: $a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => & ...

Creating a self-updating dynamic component: A step-by-step guide

Currently, I am working on a component that receives another component via props to render. However, this component has the ability to update and change itself. The issue arises when the first time it is changed, the component functions correctly but crash ...