Search code examples
javascriptarraysgoogle-cloud-functionsnested-loopspdfmake

Looping through two separate arrays for PDFmake table


I am trying to create a pdfmake table that has the array keys as a column and the corresponding array values as the next column.

Below is the JSON of 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 aim is to have a table that is kind of like:

PROPERTY      |    BENEFICIARY

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

Below is the code I have tried but it does not quite come out neatly:

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

        const assets = [];
        const benef = [];

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

     

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}`, `${benef}`, {text: '{beneficiary address}'}]
                ]
            }
        },

Is there a way to loop through the assets array and the beneficiary array maybe with a foreach that produces something like

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

on and on?


Solution

  • let rows = [
      ['Property', 'Beneficiary']
    ];
    for (let i = 0; i < assets.length; i +=1) { // i suggest a for-loop since you need both arrays at a time 
      rows.push([assets[i], benef[i]]);
    }
    

    table: {
      body: rows,
      headerRows: 1
    }