Value check within Object is not working

Asked

Viewed 29 times

-1

Hello,

I have an API that returns to me:

{
    "resultSetMetadata": {
        "count": 63,
        "offset": 0,
        "limit": 100
    },
    "results": [
        {
            "receivableBillId": 2048,
            "installmentId": 1,
            "conditionTypeId": "AT",
            "dueDate": "2019-12-27",
            "balanceDue": 0.0,
            "generatedBoleto": true
        },
        {
            "receivableBillId": 2048,
            "installmentId": 2,
            "conditionTypeId": "AT",
            "dueDate": "2020-01-27",
            "balanceDue": 1000,
            "generatedBoleto": true
        },

and so it goes.

I want a code return me the installmendId that meets the given conditions balanceDue > 0 and generatedBoleto = true. In this example the output of installmentId would be = 2

var response = JSON.parse(responseBody);
if (response.balanceDue > 0){
    if (response.generatedBoleto = true){
    numeroParcela = response.installmentId
}}
console.log(numeroParcela)

But when running this code, it gives the following error: Referenceerror: numeroParcela is not defined what is wrong ?

  • 1

    balanceDue is a key inside objects of an array called results within the response. Soon, response.balanceDue will always give Undefined because there is, and with that, the variable numeroParcela, that is within a condition that was not satisfied, does not exist when the console.log is executed. Without citing the simple signal error = within if.

  • How do I check the key values then ?

  • You have to go through the array. It could be with a for.

  • var Response = JSON.parse(responseBody); var numeroParcela = 0; var key = 0; for (key in Response) { if (Response[key].balanceDue > 1){ if (Response[key].generatedBoleto == false){ numeroParcela === = Response[key]. installmentId; }} ++key; } console.log(numeroParcela) ?

1 answer

-1

In your code you are doing the check of response.generatedBoleto with a = only and not with 2 or 3 (where 2 checks if it is equal and 3 checks if even the data type is equal), that is, the condition is wrong, which is preventing the code from entering this if and thus assign the value to the numeroParcela. Also remembering that the variable numeroParcela must be started before.

    var response = JSON.parse(responseBody);
if (response.balanceDue > 0){
    if (response.generatedBoleto == true){
    numeroParcela = response.installmentId
}}
console.log(numeroParcela)
  • This is not the only problem. See my comment above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.