Michael Tomas
Michael Tomas

Reputation: 25

How to skip comma if value is empty?

I want to create a message. Whether it is irrelevant in the html or ts file, it is only important that if a field is empty, skip comma ?

<span> Personal data: {{ data.firstName }} , {{ data.lastName }} , {{ data.age }}

At some point firstName or lastName or age is empty and then the comma remains unnecessary? Example be:

Michael , , 21

or , , 21 ..

I want if no value , no print comma.

Upvotes: 0

Views: 1096

Answers (4)

Log in
Log in

Reputation: 65

  1. [data.firstName, data.lastName, data.age ].filter(v=>v).join(" , ")

  2. Object.values(data).filter(v=>v).join(" , ")

Upvotes: 1

Pouya Jabbarisani
Pouya Jabbarisani

Reputation: 1121

Another clean solution:

Method:

calculateData(data: any) {
    return Object.keys(data).map(i => data[i] ? data[i] + ', ' : '').join('').slice(0,-2); 
}

And use like this:

<span> data: {{ calculateData(data) }}</span>
  1. get an array of keys using Object.keys(data); // ['firstName', 'lastName', 'age'].
  2. map those keys and get related data from data object using that keys
  3. check is there any value, if exist, add it with a comma
  4. join the final array (map result) to create a string
  5. remove final comma and space using .slice() method

Upvotes: 1

KShewengger
KShewengger

Reputation: 8269

You can implement it like this instead:

Template

<span> Personal data: {{ getPersonalData(data) }}</span>

Component

@Component({...})
export class AppComponent {

   ...

   getPersonalData({ firstName = '', lastName = '', age = null }) {
      return `${firstName} ${lastName} ${age ? age : ''}`
        .split(' ')
        .filter(Boolean)
        .join(', ');
   }

}

Alternative Solution

As per Michael Geary's concern below if in case either firstName or lastName has 2 or more words

getPersonalData({ firstName = '', lastName = '', age = null }) {
  return Object
    .entries({ firstName, lastName, age })
    .map(([, value]) => value)
    .filter(Boolean)
    .join(', ');
}

Have created a Stackblitz Demo for your reference containing all various scenarios when either firstName, lastName, or age is empty.

Upvotes: 1

Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1279

You need to write your own code for this: in ts file you can create the following function:

f(data): string {
  let a: string[] = [];
  if(data.firstname && data.firstname != "") a.push(data.firstname);
  if(data.lastname && data.lastname != "") a.push(data.lastname);
  if(data.age && data.age != "") a.push(data.age);
  return a.join(" , ");
}

And later in the HTML side:

<span> Personal data: {{ f(data) }} </span>

Upvotes: 2

Related Questions