Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing this using a for loop function, but unfortunately, my code did not work as expected.

Here is the data I am working with:

let myData = [
                {
                    Name: 'Section 1', 
                    Details:[
                        { Product: 'Ballpen', Quantity: 120},
                        { Product: 'Pencil', Quantity: 120},
                        { Product: 'Marker', Quantity: 80},
                        { Product: 'Highlighter', Quantity: 120}
                    ]
                },
                {
                    Name: 'Section 2', 
                    Details:[
                        { Product: 'Paper', Quantity: 40},
                        { Product: 'Bond Paper', Quantity: 75},
                        { Product: 'Colored Paper', Quantity: 75},
                        { Product: 'Oslo paper', Quantity: 40}
                    ],
                }
            ]

Expected Result: The table will look like this...


  • PRODUCT * Quantity * Count *

  • Ballpen * 120 * 2 *
  • Pencil * 120 * 2 *
  • Marker * 80 * 1 *
  • Highlighter * 120 * 1 *

This means that it will count every time the quantity of a product matches the quantity of the next element. The counting stops even if there are other elements with the same value, but they are not consecutive.

※ On the Console.log(). It will appear as...

Section 1 : {
                [ Product = 'Ballpen', Quantity = 120 , Count = 2],
                [ Product = 'Pencil', Quantity = 120 , Count = 2],
                [ Product = 'Marker', Quantity = 80 , Count = 1],
                [ Product = 'Highlighter', Quantity = 120 , Count = 1],
            },
Section 2 : {
                [ Product = 'Paper', Quantity = 40 , Count = 1],
                [ Product = 'Bond Paper', Quantity = 75 , Count = 2],
                [ Product = 'Colored Paper', Quantity = 75 , Count = 2],
                [ Product = 'Oslo paper', Quantity = 40 , Count = 1],
            },
//Other codes here...

I apologize for any confusion, as I am still learning how to manipulate data. Thank you for your patience and understanding. :)

Answer №1

I trust this meets your requirements

let myData = [
                {
                    Name: 'Department A', 
                    Details:[
                        { Item: 'Desk', Quantity: 10},
                        { Item: 'Chair', Quantity: 15},
                        { Item: 'Lamp', Quantity: 5},
                        { Item: 'Shelf', Quantity: 12},
                    ]
                },
                {
                    Name: 'Department B', 
                    Details:[
                        { Item: 'Computer', Quantity: 20},
                        { Item: 'Keyboard', Quantity: 25},
                        { Item: 'Mouse', Quantity: 30},
                        { Item: 'Monitor', Quantity: 10}
                    ],
                }
            ]
            myData.forEach((ele, idx)=>{
                ele.Details.forEach((ele2, idx2)=>{
                    let value = ele2.Quantity;
                    let count = 0;
                    let sliced = ele.Details.slice(idx2, ele.Details.length)
                    let ok = true;
                    sliced.forEach(ele3=>{
                        if (ele3.Quantity == value && ok)
                            count++;
                        else
                            ok = false
                    })

                    ele2.Count = count;
                    if(typeof ele.Details[idx2 - 1] != 'undefined')
                    {
                        if (ele.Details[idx2].Quantity == ele.Details[idx2 - 1].Quantity)
                            ele.Details[idx2].Count = ele.Details[idx2 - 1].Count
                    }
                    
                })
            })
            console.log(myData);

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

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

Establishing relationships with Sequelize between tables in different schemas

Currently, I am working on a project that involves using Sequelize and PostgreSQL as the database. In this project, I have implemented dynamic schema creation whenever a new user registers on the website. Specifically, I have a table called user_credentia ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...

Attempting to submit a form to Mailchimp with Vue.js and Axios causes a CORS error to occur

In my Vue.js application, I have a feature that sends email data from a form to Mailchimp using the Axios library. I recently learned that in order to bypass CORS restrictions when posting to Mailchimp's URL, I need to use the post-json version and a ...

Converting Javascript Variables into a PHP Script

After noticing that the same question was being asked repeatedly, I delved into thorough research to discover effective methods for transferring a couple of JavaScript variables to a PHP script. Include data in a form as hidden values Send to URL, like & ...

What is the best way to transfer a file from Postman to a Node.js server using Multer?

Windows Express version 4.12.4 Multer version 1.0.1 Node version v0.10.22 I'm currently working on sending a file to my node.js server using Postman. I'm following the instructions provided in the readme here This is what I am sending wi ...

Using Font Awesome icons with Buefy for beautiful designs

Currently, I am in the process of transitioning my project from utilizing bulma + jQuery to buefy. The resources I am loading include buefy, vue, and font awesome from a CDN. However, despite specifying the defaultIconPack as 'fas' for font aweso ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

What could be triggering the "slice is not defined" error in this TypeScript and Vue 3 application?

I have been developing a Single Page Application using Vue 3, TypeScript, and the The Movie Database (TMDB) API. In my src\components\MovieDetails.vue file, I have implemented the following: <template> <div class="row"> ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Creating a jsp page content with jquery and retrieving request parameters

I am facing an issue with my JSP page where I need to pass the value of request.getParameter("cfgname") to another content page so that it loads correctly. Currently, the code is displaying null instead of the parameter. This is the main JSP page with par ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

What could be causing the error "styled is not defined as a function" while creating my component library using Rollup?

Currently, I am facing an issue with my component library which is built using React, styled-components, framer-motion, Rollup, and Storybook. The library is being consumed by a NextJS website, but when trying to use it, I keep encountering the following e ...

Highcharts' labels on the x-axis do not automatically rotate

One issue I am facing is that my custom x-axis labels on the chart do not rotate upon window resize. I would like to have them rotated when the screen size is less than 399px. Check out the code here $(function () { $('#container').highchart ...

What is the best method for creating and passing a wrapped component to React Router?

I have multiple routes that I need to render different components for, and I want each component to be wrapped in a styled div. However, I'm looking for a way to write this code more efficiently. Is there a strategy to refactor this so that I can eas ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...