Iterating through two distinct arrays to populate a table using PDFmake

I am currently working on generating a pdfmake table with array keys in one column and the corresponding values in the next column.

Here is a snippet of the JSON from my firebase database:

{
  "users" : {
    "useruid" : {
      "wills" : {
        "assets" : {
          "MY IPHONE XR " : [ "my Brother Fab", "my sister Kenny" ],
          "bedside lamps" : [ "my cat Cuddly" ],
          "bottle " : [ "My son Ayo" ]
        },
        "details" : {
          "Daniel thompson" : "19A Silver Road "
        },
        "residual" : [ "my son Paul" ],
        "testators" : [ "my cat cuddly" ]
      }
    }
  }
}

The goal is to present the data in a table format like this:

PROPERTY      |    BENEFICIARY

MY IPHONE XR  |    MY BROTHER FAB, MY SISTER KENNY
BEDSIDE LAMPS |    MY CAT CUDDLY
BOTTLE        |    MY SON AYO

Although I have attempted some code, it does not display the information neatly:

     admin.database().ref('users').child('useruid').child('wills')
    .child('assets').once('value').then(function(dataSnapshot1) {

        const assets = [];
        const beneficiaries = [];

        dataSnapshot1.forEach((childSnapshot) => {
                      const childKey = childSnapshot.key;
                      const childData = childSnapshot.val();
                      assets.push( childKey );  
                      beneficiaries.push( childData ); 
                    });
          console.log(assets);
          console.log(beneficiaries);

     

var docDefinition = {
    content: [

        
        'I DECLARE that my Executors or any Professional or person engaged in proving my Will and administering the estate may charge reasonable fees for their services ',
        
        '\nI GIVE my property as follows:',
        
        {text: 'Property and Beneficiaries ', style: 'subheader'},
    

        {
            style: 'tableExample',
            table: {
                widths: ['*',100, '*', 200],
                body: [
                    ['No.','Property', 'Beneficiary', 'Beneficiary Address'],
                    [`${assets}`, `${beneficiaries}`, {text: '{beneficiary address}'}]
                ]
            }
        },

Is there a way to iterate through the assets and beneficiaries arrays using a loop such as foreach, which can output something similar to this:

rows= [];
rows.push([index, asset1, asset 1 beneficiaries])
rows.push([index +1, asset2, asset 2 beneficiaries])

and so forth?

Answer №1

const dataRows = [
  ['Category', 'Recipient']
];
for (let index = 0; index < items.length; index +=1) { // I recommend using a for-loop to iterate through both arrays simultaneously
  dataRows.push([items[index], recipients[index]]);
}

formattedTable: {
  content: dataRows,
  headerRowCount: 1
}

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

Troubleshooting problem with Bootstrap tooltips

I'm having a problem where my tooltip is displaying below the relevant link, no matter what I try. In the style section of my code, I have this: <style> /* Tooltip on top */ .test + .tooltip.top > .tooltip-arrow { border-top: 5px solid ...

Best practice for verifying if a form is empty in Ember.js

My form includes HTML5 validation implemented in the following way: <script type="text/x-handlebars" id="project"> <div class="row"> <div class="span6"> <div class="well well-small"> <p s ...

Establishing the direction of the projection matrix in three.js

I came across the following code snippet intended for webgl, and I am looking to rewrite it using three.js. However, I haven't been able to figure out how to do so. Can someone please assist me with this? pMatrix = mat4.create(); mat4.perspec ...

Troubleshoot the issue of ng-click not functioning properly when used in conjunction with ng-repeat with direct expressions

Having some trouble with an ng-repeat block and setting a $scope variable to true with an ng-click expression. It doesn't seem to be working as expected. Can anyone help out? Check the plnkr for more information. HTML: selected: {{selected}} < ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

Ways to conceal li elements containing values lower than the provided input number

There is a form where users input numbers and below are some elements displayed in an unordered list. The goal is to dynamically hide those elements that have a number less than the user-inputted value. <input type="text" id="myInput" onkeyup="myFuncti ...

Using Jquery Ajax to send a POST request with form data and display the server's response

I have an AJAX request to send data to an API and receive a response. I would like to know how to dynamically pass the value from an input field to the body data in the AJAX request. Here is my form: <input type="text" name="serial" /> <input ty ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

Establishing a Goal in Google Analytics using JavaScript

My approach to recording Goals in Google Analytic tool via JS involves adding code directly to the page: <meta name="description" content="iReserve"> <link rel="shortcut icon" href="/ico/favicon.ico" /> & ...

Utilizing API information to generate a dynamic table in React.js with the help of React

I've come across some examples of creating react tables with API data, but none of them utilized the header(key) from the API data to set headers in the react table. I'm seeking assistance on how to achieve this. In my code, I've retrieved ...

Retrieving data from JSON arrays based on specific conditions in Java

I have been utilizing Unirest to retrieve all IDs from an endpoint. The array structure is as follows: [ { "date": "2022-04-05", "timeIn": "2022-04-05 07:00:00", "timeOut": " ...

Is there a way to customize the shuffle function for an ArrayList containing my own objects?

Every time I try to do something like this: List<Player> players = JackpotGame.getUnsortedPlayerList(); players = Collections.shuffle(players); I keep getting an error: I know for certain that the getUnsortedPlayerList method returns a Lis ...

Implement checkbox functionality for data binding in Vue framework

I'm having trouble figuring out how to display the selected values in Vue. I've got a form that triggers a query based on the user's selections: <form id="Register"> <br>Firstname<input type="checkbox" value="firstNam ...

Customizing the start and end dates of months in PHP: A step-by-step guide

My pay cycle starts on the 26th of the previous month and ends on the 25th of the current month. For example, for February 2016, the pay cycle would be from January 26 to February 25. I am looking for the following output: $date = '2014-02-27'; ...

What steps can I take to ensure that a JavaScript function does not automatically execute when the browser loads?

I have encountered an issue with a function called onSuccess that is supposed to execute when an AJAX request is successful. The problem is that the function runs as soon as my browser loads, but I want it to only run when a button with the id "myButton" i ...

The jQuery.ajax converter function is not being triggered

I'm struggling with jQuery.ajax converters - my converter function isn't triggering. This is the simplified jQuery AJAX code I'm using: $.ajax({ url: "http://myurl/myservice", dataType: "JSONP", cache: false, success: ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Prevent the change event from firing when the page loads in JavaScript - what can be done to avoid

Dealing with a form that contains chained select boxes can be quite challenging. Particularly when the Zend controller is involved in setting default values for these select boxes, which are pulled from the database. As someone who is new to jQuery, naviga ...

Changing the row color in a Jquery dataTable

Trying to utilize JQuery datatable, Wanting to modify the row color when hovered over (the highlighted row) Attempted solution: table.display tr.even.row_selected td { background-color: red; } table.display tr.odd.row_selected td { backgroun ...

Is React State with JSON Object Losing Updates?

Encountering a strange issue here. At the start of my program, I load various values into a JSON object stored as a User State Object in a Postgres table. Although the object is quite large, I'll provide an example below. const [person, setPerson] = u ...