Home > Blockchain >  How to get the sum of two object keys that meet a condition
How to get the sum of two object keys that meet a condition

Time:09-27

I have one obj which has the following key/values

var pay = [
  {
    journal: 23,
    regdate: "31/08/2021",
    account: "2.1.01.0001.02181 Folha de Pagamento:Salarios a Pagar",
    debitvalue: "3003,58",
    creditvalue: "",
    itemdescrip: "Valor ref folha de pgto, mês 08/2021",
    name: "",
    branch: "",
    costcenter: "",
    message: "",
  },
  {
    journal: 23,
    regdate: "31/08/2021",
    account: "2.1.01.0001.02181 Folha de Pagamento:Salarios a Pagar",
    debitvalue: "",
    creditvalue: "4003,58",
    itemdescrip: "Valor ref folha de pgto, mês 08/2021",
    name: "",
    branch: "",
    costcenter: "",
    message: "",
  },
];

I would like to subtract all the "debitvalue" from "creditvalue" where a condition is met, i.e. account key contains 2.1.01.0001.02181

I've tried map, filter, indexOf, contains and all of which returns [].

Expected result should be 3.000 I'm beginning with javascript and I don't know too much. Thanks.

CodePudding user response:

Something like this will work.

let diff

pay.forEach((obj) => {
  if (obj.account.includes('2.1.01.0001.02181')) {
    let credit = parseInt(obj['creditvalue'].replace(/,/g, '.')) || 0
    let debit = parseInt(obj['debitvalue'].replace(/,/g, '.')) || 0

    diff = credit - debit
  }
})

console.log(diff)

I threw in some regex to deal with the commas in your data.

CodePudding user response:

You can do it with simple array functions as .reduce

var pay = [
  {
    journal: 23,
    regdate: "31/08/2021",
    account: "4.1.01.0001.04200 Despesas com folha de pagamento:Salarios",
    debitvalue: "4003.58",
    creditvalue: "",
    itemdescrip: "Valor ref folha de pgto, mês 08/2021",
    name: "",
    branch: "",
    costcenter: "",
    message: "",
  },
  {
    journal: 23,
    regdate: "31/08/2021",
    account: "2.1.01.0001.02181 Folha de Pagamento:Salarios a Pagar",
    debitvalue: "",
    creditvalue: "4003.58",
    itemdescrip: "Valor ref folha de pgto, mês 08/2021",
    name: "",
    branch: "",
    costcenter: "",
    message: "",
  },
];

const totalAmount = pay.reduce( (total, currentPay) => {
    
    if (currentPay.account.includes("2.1.01.0001.02181")) {
        total = total    currentPay.creditvalue - currentPay.debitvalue;
    }
    return total;
  }, 0)

console.log(totalAmount);

CodePudding user response:

To achieve my needs I used the collaboration of the lads to implement the following code

const totalAmount = fDataAccount.reduce( (total, currentPay) => {
    
      if (currentPay.account.includes(payacc)) {
          var d = parseFloat(currentPay.debitvalue.replace(/,/g, '.')) || 0;
          var c = parseFloat(currentPay.creditvalue.replace(/,/g, '.')) || 0;

          total  =  c - d;
      }
      return total;
      }, 0)

Thanks guys!

  • Related