A
A
Alexey Sklyarov2019-03-08 12:20:23
Vue.js
Alexey Sklyarov, 2019-03-08 12:20:23

How to correctly write a check for the values ​​of the keys of an object for emptiness, the key value can also be an object?

There is an object in data():

data: function() {
  return {
      car: {
        model:null,
        year:null,
        power:null,
        number:null,
        doc: {
          type: null,
          number: null,
          date:null,
        },
        card: {
          item: null,
          date: null,
        },
        card_our: false,
        vin: '',
        body_number: '',
        chassis_number:''
   },
 }
}

There is a method that runs the keys of the desired object and if any of them is equal to an empty value or null, it does not allow to proceed to the next step of filling out the form.
validateObject: function(obj,exclude = null) {
      obj = Object.assign({}, obj);
      for (let key in obj) {
        if (exclude && exclude.includes(key)) continue;
        if (obj[key] == null || obj[key] == '') return false;
      }
      return true;
    },

What it does:
1. Converts the vue object's observer to a normal object.
2. An array of keys excluded from the check is passed to exclude.
3. As you fill in the data from the form, checks this data. If some required data is missing, false is returned and you cannot proceed to the next step.
What the problems are:
Can't currently check for keys whose value is an object because it's already an observer object that needs to be converted again.
You can, of course, do a typeof check, and if it's an object, do the conversion and go through it, but what if the nesting is large?
I have a bad idea of ​​already going inside the object through several levels (but in my task there are a maximum of 2), how can this be done? You need to convert the nested object itself and check more keys for it. It turns out an endless veil of cycles in a cycle?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-03-08
@0example

When in the function loop you realize that you have collided with an object, then you just need to call the same function again, but pass this object as the value. This is called recursion ( https://learn.javascript.ru/recursion)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question