Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need.

I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with the following example:

{
    "total": 563,
    "shipping_fee": 58,
    "e_charges": ???,
    "order_items": [
      {
        "item_id": 6291020872,
        "quantity": 1,
        "price": 88,
        "total": 88
      },
      {
        "item_id": 7755274567,
        "quantity": 1,
        "price": 150,
        "total": 150
      },
      {
        "item_id": 7980571205,
        "quantity": 1,
        "price": 45,
        "total": 45
      },
      {
        "item_id": 12612977930,
        "quantity": 1,
        "price": 280,
        "total": 280
      }
    ]
  }, ... {} {} {}....

My issue is calculating the total sum of all total values in order_items [], then adding the shipping_fee and calculating two separate percentages.

  1. 10%
  2. 8%

It's important to note that I'm receiving these values in real-time.

const resDetails = await request.post(baseURL, {
        data: viewData
    });

info = await JSON.parse(JSON.stringify(await resDetails.json()));

Here is how the JSON file structure was derived:

orders = await info.data.orders.map((x) => ({total: x.order_items.map(y =>  Number(y.order_price) * y.amount).reduce((total, y) => y+total),
        shipping_fee : Number(x.shipping_fee), 
        e_charges: Number(Number((x.order_items.map(y=>  Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed()),
        order_items: x.order_items.map((y) => ({
             item_id : y.item_id, 
             quantity: y.amount, 
             price: Number(y.order_price),
             total: Number(y.order_price) * y.amount}))})

I managed to calculate the 10%, but I'm struggling to add the additional 8% without repeating the mapping, reducing, and adding the shipping_fee again.

Number(Number((x.order_items.map(y=>  Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed())

I'm new to the world of JavaScript/TypeScript and I'm hoping for a more efficient way to achieve my goal. Thank you for any assistance.

EDIT: Here's the actual code: https://i.sstatic.net/bcHHI.png

Answer №1

Feel free to review the code snippet below. Personally, I prefer not to cram all the calculations into one line using the map, reduce, and other functions as it can make the code less readable. Instead, I have broken down the calculations into separate methods.

One important point to note is that the total order amount is computed only once, and the percentage charges for e_charges are saved in two different keys - e_charges_8 and e_charges_10. This structure allows for easy customization according to specific requirements.

let orders = [
  {
    "shipping_fee": 58,
    "order_items": [
      {
        "item_id": 6291020872,
        "quantity": 1,
        "price": 88
      },
      {
        "item_id": 7755274567,
        "quantity": 1,
        "price": 150
      },
      {
        "item_id": 7980571205,
        "quantity": 1,
        "price": 45
      },
      {
        "item_id": 12612977930,
        "quantity": 1,
        "price": 280
      }
    ]
  }, 
  {
    "shipping_fee": 58,
    "order_items": [
      {
        "item_id": 6291020872,
        "quantity": 1,
        "price": 88
      },
      {
        "item_id": 7755274567,
        "quantity": 1,
        "price": 150
      },
      {
        "item_id": 7980571205,
        "quantity": 1,
        "price": 45
      },
      {
        "item_id": 12612977930,
        "quantity": 1,
        "price": 280
      }
    ]
  }
]


const getOrderItemTotal = (orderItem) => {
  return orderItem.quantity * orderItem.price
}

const getPercentage = (shippingFee, total, percentage) => {
  return ((total + shippingFee) * percentage).toFixed()
}

const getOrderItemsTotal = (orderItems) => {
  return orderItems.reduce((total, orderItem) => (total + orderItem.total), 0)
}

orders = orders.map(order => {
  order.order_items.map(orderItem => {
    orderItem.total = getOrderItemTotal(orderItem)
    return orderItem
  })
  
  order.total = getOrderItemsTotal(order.order_items)
  
  order.e_charges_8 = getPercentage(order.shipping_fee, order.total, 0.1)
  order.e_charges_10 = getPercentage(order.shipping_fee, order.total, 0.08)
    
  return order
})


console.log(orders)

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

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

How can a parameter be added to a query string only when there is a value present in a textbox using JavaScript?

Hello everyone, I am looking to add parameters to a URL only if the search text box value is different from the default. I have three search text boxes and I want to include them in the URL. Below is my code snippet: $("#search-btn").click(function (e) { ...

Limiting the size of images within a specific section using CSS

When using CSS, I know how to resize images with the code snippets below: img {width:100%; height: auto; } img {max-width: 600px} While this method works effectively, it applies to every image on the page. What I really need is for some images to be ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Steps for injecting strings directly into Angular2 EventBindingWould you like to learn how

Is it feasible to achieve something similar to this? <li><a href="#" target="_blank" (click)="createComponent(MYSTRINGHERE)">Departamentos</a></li> ...

Setting a default value in react-select

Recently, I developed a react-select component that is compatible with redux-form. The SelectInput component looks like this: const MySelect = props => ( <Select {...props} value={props.input.value} onChange={value => props.input.on ...

Using Web SQL always seems to throw me for a loop

I attempted to populate a web SQL database with some data, but encountered an issue. Here is my code: database(); for(var i=0; i<m.length; i++){ showid = m[i].id; showtitle = m[i].title; insert(); } function database(){ //open the database ...

"I'm looking for a way to set a cookie and JSON in the server response and then redirect to the client URL using PassportJS in

I am trying to set a cookie with HTTP only in the server using Passport.js ("Google"). After setting the cookie, I need to redirect, but I am encountering an error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ...

Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other but ...

Unknown identifier in the onClick function

I want to create a JavaScript function that can show or hide a paragraph when clicking on an arrow. The challenge I'm facing is that I have a list of titles generated in a loop on the server, and each title is accompanied by an arrow. Initially, the c ...

Transmit information from the primary HTML page's controller to a directive's controller

After researching various sources such as blogs and stackoverflow, I was unable to find a solution to my specific problem of communicating between controllers and directives. Many concepts I found were for case-specific issues, but none seemed to fit my ne ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...

Once this code is executed, Javascript ceases to function

I have developed a code snippet to create a typing effect similar to a command console. While the code is functioning well on its own, any additional code I add after it seems to malfunction. I've spent quite some time troubleshooting this issue witho ...

The event.pageY position consistently reflects the laptop screen size rather than the exact position where the click occurred

My webpage is scrollable, but the event.pageY position always corresponds to my screen size. Even when scrolling down and clicking near the top of the screen, it registers as 50px. I am currently utilizing event.pageY While this functions correctly on a ...

What is the method for retrieving the active element with Waypoint?

Currently, I am implementing Waypoint (version 7.3.2) in my React project using React version 16. My goal is to create a scrollable list of items where each item fades out as it reaches the top of the container div. My main inquiry is how can I obtain a re ...

Enhance the design of MDX in Next.js with a personalized layout

For my Next.js website, I aim to incorporate MDX and TypeScript-React pages. The goal is to have MDX pages automatically rendered with a default layout (such as applied styles, headers, footers) for ease of use by non-technical users when adding new pages. ...

Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables ...

Can you provide guidance on how to access my account using the code that I have?

I'm having trouble getting the login functionality to work properly with this code. When I click the login button, nothing happens - no errors are displayed either. Can you help me identify what might be causing this issue? login() { var url = &ap ...

Is it possible for JavaScript to be cached when it is located within the body tag of an HTML document?

Currently, I am exploring the topic of How to optimize HTML rendering speed, and came across the idea that scripts in the HEAD tag can be cached. I'm curious, is it possible to cache JavaScript in the BODY tag? If not, I wonder why YUI suggests placi ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...