My inaccessible JSON key for Node.js validation

Asked

Viewed 54 times

1

I am developing an API in Node.js and Knex.js, but I came across a problem, the array that Knex returns in the promise has a JSON inside and is numerical that needs to be validated. However, the key is strange and cannot access its value, so I cannot make a correct answer.

Code:

async dateValidator(request, response){
    const {loja, data} = request.body;
    const queryCountData = conection('agendamentos').count("data").where({"data": data, 'loja': loja});
    queryCountData.then(resp => {
        if(resp[0].count >= 13){
        response.status(401).json(resp);
        }
        if(resp < 13){
            response.status(201).json(resp);
        }
    }); 
}

The resulting JSON:

[
  {
    "count(data)": 13
  }
]

The key to the object is count(data). How do I access this object in Javascript, and it has parentheses (()) within?

1 answer

1


According to the knex documentation, you can pass an option as to rename the field count(data):

.count('data', { as: 'data' })

From there the key of the objects returned to this field will be data, and no more count(`data`):

resp[0].count // OK

As a curiosity, this key is not "inaccessible". In cases like this, the bracket notation should be used for access, since parentheses are not valid identifiers in Javascript:

resp[0]['count(data)'] // OK

Note that it is possible to access keys with any type of character through this notation:

const strangeObject = {
  'count(data)': 10,
  '': 20
};

console.log(strangeObject['count(data)']); // 10
console.log(strangeObject['']); // 20

  • I had totally forgotten the option "as" I’m now picking up the knex, I dealt with sql straight and was altomatic this ja, but with the knex is all new

  • face thank you really

Browser other questions tagged

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