Correct way to check if field exists in Javascript (or framework)?


dj

I guess this generally applies to all JS, but what is the correct way to override this computed method to ensure it doesn't fail if the field is not available?

computed() {
   isVerified() {
        return this.name.info.is_valid;
   }
}

I can do it, but it would be wordy:

computed() {
   isVerified() {
        if (this.name && this.name.info && this.name.info.is_valid) {
           return true;
        } else {
           return false;
        }
   }
}
people

Combining optional chaining with the void coalescing operator seems appropriate in your case .

computed() {
  isVerified() {
    return this.name?.info?.is_valid ?? false;
  }
}

Returns (boolean) if there are any this.name, this.name.infoeither or . Otherwise returns the current value , whatever it can be (including any falsey value other than ie : , , ).this.name.info.is_validnullundefinedisVerifiedfalsethis.name.info.is_validnullundefined0''NaN


Keep in mind that the following list of browsers do not support these two operators at the moment:

  • Internet Explorer
  • Android版Firefox
  • Opera for Android
  • samsung internet

Check out its current implementation status at caniuse.com:


Note about the latest Vue 2( v2.6.11) usage: both operators only work inside components (methods, computed, hooks, etc.), but they will error out if used directly in templates.
Haven't tested in Vue 3, but I expect them to work (as of v3.7 they are valid TypeScript operators ).

For purists this is

function isValid(name) {
  return name?.info?.is_valid ?? false;
}

...in the Tower of Babel:

"use strict";

function isValid(name) {
  var _name$info$is_valid, _name$info;

  return (_name$info$is_valid = name === null || name === void 0
          ? void 0
          : (_name$info = name.info) === null || _name$info === void 0
            ? void 0
            : _name$info.is_valid
         ) !== null && _name$info$is_valid !== void 0
          ? _name$info$is_valid
          : false;
}

Related


What is the correct way to check if a global variable exists?

Ebrahim Byagowi: JSLint is not passing this as valid code: /* global someVar: false */ if (typeof someVar === "undefined") { var someVar = "hi!"; } What is the correct way? bigoldbrute: /*global window */ if (window.someVar === undefined) { window.so

Best way to check if field exists in Elasticsearch document

Storm Hernandez Troyas Probably a very stupid question, what is the best way to check if a document field exists in Elasticsearch? I can't find anything in the documentation. For example, if the document doesn't have the field/keyword "price", then I don't wan

Correct way to check if DocumentDB object exists

Strenikovlev In Microsoft's example, I see two methods to check if a DocumentDb object exists, such as Database, DocumentCollection, Document, etc: The first is by creating a query: Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEn

Is this the correct way to check if a file exists?

beginner I'm trying to check if a file (image) exists so I can delete it before uploading a new one. Here's what I've tried so far: foreach (glob("../imgs/" . $name . ".*") as $file) { if (file_exists($file)) { unlink($file); } } Is this the c

What is the correct way to check if a global variable exists?

Ebrahim Byagowi: JSLint is not passing this as valid code: /* global someVar: false */ if (typeof someVar === "undefined") { var someVar = "hi!"; } What is the correct way? bigoldbrute: /*global window */ if (window.someVar === undefined) { window.so

Correct way to check if file exists in Linux

Brian I've been using it in my scripts but my colleagues disagree with me. My script accepts a file as a parameter and creates that file. Then I use the following to see if it actually gets created. ls -p | grep [filename] Then I check to see if the file I'm t

What is the correct way to check if an array exists in JS?

Hussein When I check the length of the array, I get the following error. What is the correct way? main file if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) { //code goes here } mistake TypeError: Can

Best way to check if field exists in Elasticsearch document

Storm Hernandez Troyas Probably a very stupid question, what is the best way to check if a document field exists in Elasticsearch? I can't find anything in the documentation. For example, if the document doesn't have the field/keyword "price", then I don't wan

Correct way to check if DocumentDB object exists

Strenikovlev In Microsoft's example, I see two methods to check if a DocumentDb object exists, such as Database, DocumentCollection, Document, etc: The first is by creating a query: Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEn

Correct way to check if DocumentDB object exists

Strenikovlev In Microsoft's example, I see two methods to check if a DocumentDb object exists, such as Database, DocumentCollection, Document, etc: The first is by creating a query: Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEn

Is this the correct way to check if a file exists?

beginner I'm trying to check if a file (image) exists so I can delete it before uploading a new one. Here's what I've tried so far: foreach (glob("../imgs/" . $name . ".*") as $file) { if (file_exists($file)) { unlink($file); } } Is this the c

What is the correct way to check if a collection exists?

Tim Previously, I checked if the collection existed by querying the namespace. Roughly like this, check if "foo.bar" exists: return 1 === $client->selectCollection('foo','system.namespaces'); ->count(['name'=>'bar']); Since this only works

What is the correct way to check if an array exists in JS?

Hussein When I check the length of the array, I get the following error. What is the correct way? main file if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) { //code goes here } mistake TypeError: Can

What is the correct way to check if a global variable exists?

Ebrahim Byagowi: JSLint is not passing this as valid code: /* global someVar: false */ if (typeof someVar === "undefined") { var someVar = "hi!"; } What is the correct way? bigoldbrute: /*global window */ if (window.someVar === undefined) { window.so

Best way to check if field exists in Elasticsearch document

Storm Hernandez Troyas Probably a very stupid question, what is the best way to check if a document field exists in Elasticsearch? I can't find anything in the documentation. For example, if the document doesn't have the field/keyword "price", then I don't wan

Best way to check if field exists in Elasticsearch document

Storm Hernandez Troyas Probably a very stupid question, what is the best way to check if a document field exists in Elasticsearch? I can't find anything in the documentation. For example, if the document doesn't have the field/keyword "price", then I don't wan

Correct way to check if DocumentDB object exists

Strenikovlev In Microsoft's example, I see two methods to check if a DocumentDb object exists, such as Database, DocumentCollection, Document, etc: The first is by creating a query: Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEn

Correct way to check if DocumentDB object exists

Strenikovlev In Microsoft's example, I see two methods to check if a DocumentDb object exists, such as Database, DocumentCollection, Document, etc: The first is by creating a query: Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEn

Is this the correct way to check if a file exists?

beginner I'm trying to check if a file (image) exists so I can delete it before uploading a new one. Here's what I've tried so far: foreach (glob("../imgs/" . $name . ".*") as $file) { if (file_exists($file)) { unlink($file); } } Is this the c

What is the correct way to check if a collection exists?

Tim Previously, I checked if the collection existed by querying the namespace. Roughly like this, check if "foo.bar" exists: return 1 === $client->selectCollection('foo','system.namespaces'); ->count(['name'=>'bar']); Since this only works