0

I have some json code within a function that looks like this:

getFields(name: string) {
   this.json_data = [
      {
        "e_name": "fake_c",
        "fields": [
          {
            "f_name": "c_name",
            "title": "K C Name",
            "c_name": "cname",
            "path": this.dialogData.name
          },
          {
            "f_name": "c_number",
            "title": "K C Number",
            "c_name": "cnumber",
            "path": this.dialogData.c_id
          }
        ]
      },
      {
        "e_name": "other_c",
        "fields": [
          {
            "f_name": "c_name",
            "title": "K C Name",
            "c_name": "cname",
            "path": this.dialogData.r_name
          },
          {
            "f_name": "c_address",
            "title": "K C Address",
            "c_name": "caddress",
            "path": this.dialogData.r_address
          },
          {
            "f_name": "c_number",
            "title": "K C Number",
            "c_name": "cnumber",
            "path": this.dialogData.r_number
          }
        ]
      }
    ];
   return this.known_company_mapping.filter((d)=> d.entity_name === name).map((res) => res.fields)[0]

As you can see, based on the e_name, I am filtering the json.

However, my code is breaking due to the path that refers to dialogData.

When e_name is equal to 'fake_c', then the dialogData follows the structure that is used in the 'fake_c' paths, eg it contains a name and c_id component.

However, when 'fake_c' is used, then the paths for other_c breaks as the dialogData doesn't have r_name for example. When 'fake_c' is being used, I'm not interested in the paths for 'other_c'.

Is there any way I can make the path equal to null if the variable doesn't exist?

I've tried the below with no success:

"path": if(this.dialogData.r_name) {this.dialogData.r_name} else {''}

And also the below:

"path": this.dialogData.r_name ? this.dialogData.r_name : ''

1 Answer 1

1

the following quick if must work:

(this.dialogData.r_name ? this.dialogData.r_name : "")

as you can see in the example below.

make sure that your program re-built after each try, and that the quick if is actually running using

debugger;

or breakpoints.

this.dialogData={};
this.dialogData.r_name="test";
console.log({"path": (this.dialogData.r_name ? this.dialogData.r_name : "")});
this.dialogData.r_name=undefined;
console.log({"path": (this.dialogData.r_name ? this.dialogData.r_name : "")});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.