Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to add object to array returns Undefined

I have the following code which I try to add some objects to the array with two existing objects through a function but it always returns undefined and I don’t know how to solve it.

let compte = {
  iban: "ES79 2100 0813 6101 2345 6789",

  saldo_inicial: 15000,

  operacions: [{
    quantitat: 1200,
    concepte: 'X',
    data_operacio: new Date(Date.now()),
  }, {
    quantitat: -100,
    concepte: 'X',
    data_operacio: new Date(Date.now()),
  }],

  afegir_operacio: function(quantitat, concepte, data_operacio) {
    compte.operacions.push({
      quantitat: quantitat,
      concepte: concepte,
      data_operacio: data_operacio
    });
    console.log(compte.operacions);
  }
}

compte.afegir_operacio({
  quantitat: -100,
  concepte: "Factura",
  data_operacio: "3-10-2021"
});
compte.afegir_operacio({
  quantitat: -50,
  concepte: "Compra"
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You get undefined because the data you’re trying to add is not what you’re passing to the function. Take a look at the corrections. When you do not pass a value for a given property, you’ll get undefined for that property unless you define a default value:

let compte = {
        iban: "ES79 2100 0813 6101 2345 6789",
    
        saldo_inicial : 15000,
    
        operacions: [{
            quantitat: 1200,
            concepte: 'X',
            data_operacio: new Date(Date.now()),
        }, {
            quantitat: -100,
            concepte: 'X',
            data_operacio: new Date(Date.now()),
        }],
    
        afegir_operacio: function ({quantitat, concepte, data_operacio = "default_value"}) {
            this.operacions.push({quantitat: quantitat, concepte: concepte, data_operacio: data_operacio});
            console.log(this.operacions);
        }
    }
    
    compte.afegir_operacio({ quantitat: -100 , concepte: "Factura", data_operacio: "3-10-2021" });
    compte.afegir_operacio({ quantitat: -50, concepte: "Compra" });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading