Using Vue JS to extract and merge data from an API response in JSON format

Hey there! I'm a new developer working with Vue JS. I have a response body where I need to sum the amount values that have is_paid:true using only the paid_amount. Can someone guide me on how to achieve this in Vue JS?

Edit: For example, I want to add up 30 (amount) and 20 (

paid_amount>), excluding 100 as it has <code>is_paid:false
.

{
    "payment" : {
        "installment_payment" : {
            "installments" : [
                          amount:30,
                                date: "",
                                is_paid: true,
                            },
                            {
                                amount: 100,
                                date: "",
                                is_paid: false,

                            },
                            {
                                amount: "",
                                date: "",
                                is_paid: false,
                            },
                              {
                                amount: "",
                                date: "",
                                is_paid: true,
                            }
                        ],

                        remaining: ""

                    },
                    paid_amount: 20,
                },

}

Answer №1

Looking to filter out paid installments....

let installments = apiResponse.payment.installment_payment.installments;
let paidInstallments = installments.filter(obj => obj.is_paid);

Calculating total using reduce...

let totalPaid = paidInstallments.reduce((sum, obj) => sum + parseInt(obj.amount), 0);

Check out this demonstration...

let installments = [
  { amount:5, is_paid:true }, { amount:10, is_paid:false },
  { amount:15, is_paid:true }, { amount:20, is_paid:false }
];

// 5 and 15 are paid, so total should be 20
let paidInstallments = installments.filter(obj => obj.is_paid);
let totalPaid = paidInstallments.reduce((sum, obj) => sum + parseInt(obj.amount), 0);
console.log(totalPaid);

You can also achieve filtering and reducing in one step, for example like this...

// Filter all installments and set payment as 0 when not paid
let totalPaid = installments.reduce((sum, obj) => {
  const amountPaid = obj.is_paid ? parseInt(obj.amount) : 0;
  return sum + amountPaid;
}, 0);
console.log(totalPaid);

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

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Data not being properly set in the form

Check out this chunk of HTML code: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> function getCords(){ ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

Switching between TWO classes in Vuejs

I've been grappling with how to add or remove TWO classes in Vue JS for hours. The documentation examples only demonstrate toggling one class. My goal is to change a button's class to either: active toggle-on or toggle-off when clicked. While ...

search through an object to find specific data

Here is a JavaScript object that I have: var data = { "type": [ "car", "bike" ], "wheels": [ "4", "2" ], "open": [ "Jan", "Jan" ] ...

The benefits of installing gulp plugins locally versus globally

Being a newcomer to Gulp, I have a query: should I install gulp plugins (like gulp-sass or gulp-imagemin) locally or globally? Most online examples suggest installing them locally using the --save-dev option. This method saves the modules in the local node ...

Can you eliminate data errors within a Vue component?

In my Vue instance, I will be making a multitude of API calls to modify various variables. The initial value of these variables is not crucial. I had hoped there might be a way to avoid defining them upon the creation of the vm, but this approach doesn&ap ...

Regular Expression: Identify specific characters at the start or end of a string

I am in need of a regular expression (regex) that can precisely match the char set 'AB' only if it is at the beginning or end of a string, and then replace it with an empty string. It is important to note that the regex should not match parts of ...

bridging information from tables with text fields in forms

I am working on an HTML/CSS page that utilizes a table layout filled with buttons to mimic a T9 keypad design. Within the page, I have a form containing two text fields. My aim is to populate these text fields with numbers based on the values from the tab ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Automatic line breaks within a JavaScript code can be achieved by using

I need help formatting this text: hello everyone. My name is PETER. hahahah ahahah .... If I have a fixed width, how can I automatically line break the text to look like this: hello everyone. My name is PETER. hahahah ahahah ...

Acquire the item that is found in every array (Javascript)

In my data, I have multiple arrays like the following: { names: [0, 1, 2], gender: [2, 5, 1], boolean: [7, 2, 1, 6] } Is there a way to extract the value that appears in all arrays? For example, how can I retrieve the value 1 since it is prese ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

AngularJS Compile directive allows you to specify functions that you want to run in

Can someone assist me in understanding how to call an external function from a built-in compile directive? Here is a code example: http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview This is the HTML: <!DOCTYPE html> <html ng-app="app"> ...

What are the steps to collapse React state in a comments section?

Here is the data I have: { "currentUser": { "image": { "png": "/src/assets/images/avatars/image-juliusomo.png", "webp": "/src/assets/images/avatars/image-juliusomo.webp" }, ...

What strategies can be utilized to enhance the cleanliness of these functions?

Is there a way to avoid adding new lines of JS code every time I add a new image to the HTML? $(document).ready(function() { $('.btn').click(function() { var bid = $(this).attr('id'); if(bid=="img1" || bid == "img2" || bid == "img3"){ ...