0

I've read the answers to this question why is typeof null "object"? and I'm trying to figure out a solution to a specific problem.

I am working on a Web application with angularJs for the front-end and ASP.NET MVC for the server code. We're passing our models to the front-end and then updated values back. Here is the situation I'm trying to find a solution for:

When we're deleting numbers from the input type="number" using a backspace key in the Web interface, the value of the input control becomes null. In our models the numeric values are defined as not nullable (and in our database the strings also should be converted to empty values instead of null).

I am trying to figure out a way to set keys to 0 if they are numeric and to empty string if they are strings.

I've added a new method called verifyInput and here is the beginning of the code:

/**
     * @returns true or false 
     * */
    Model.prototype.verifyInput = function () {
        for (let i = 0; i < this.keys.length; i++) {
            const key = this.keys[i];

            if (this[key] === null) {
                this[key] = 
            }
        }
    }

I am not sure how to write the above method. I already found out that I can not use typeof or lodash methods to check for key's type as it's returning object. I need to set numbers to 0 and strings to empty strings, but leave datetime values alone. Do you see my problem and do you have ideas of a solution? Perhaps I should use try/catch here?

Naomi
  • 718
  • 1
  • 9
  • 28
  • I was also thinking of trying to simply remove the key from the collection, but I'm not sure if the loop will work if I add delete key? – Naomi Jun 22 '18 at 23:17

1 Answers1

0

The idea I had of deleting these keys seem to work. I'm getting the correct behavior (e.g. the values automatically come as 0 in this case to the server).

I added the following code:

Model.prototype.verifyInput = function () {

        let i = this.keys.length;
        while (i--) {
            const key = this.keys[i];

            if (this[key] === null) {
                this.keys.splice(i, 1); // Let's remove the null element from the model
            }            
        }

        return true;
    }

based on another very helpful answer I found Looping through array and removing items, without breaking for loop and in the tests I made so far it worked nicely.

Naomi
  • 718
  • 1
  • 9
  • 28
  • I will need to adjust the above, I think - what if I have a complex model? E.g. collections of objects? Would this still work fine? – Naomi Jun 22 '18 at 23:47