minnu merin alex
minnu merin alex

Reputation: 97

Create an array with variables only if those contain values

I have values as per below. I have 3 variables: A,B,C. If these 3 have values like below:

 this.A= "1";
 this.B= "2";
 this.C= "3";

Then the expected array is:

let D=[{id:"1"},{id:"2"},{id:"3"}]

If the value is like below:

 this.A= "1";
 this.B="" or null;
 this.C= "3";

Then the expected array is:

let D=[{id:"1"},{id:"3"}]

Upvotes: 0

Views: 41

Answers (2)

the_louie
the_louie

Reputation: 21

In addition to Jetos excellent answer it's also possible to use Array.reduce.

const D = [this.A, this.B, this.C]
  .reduce((acc, curr) => curr === null ? acc : acc.concat([{id: curr}]), [])

Upvotes: 1

Jeto
Jeto

Reputation: 14927

You could make use of:

This becomes:

let D = [this.A, this.B, this.C]
  .filter(val => !['', null].includes(val))
  .map(val => ({id: val}));

Demo (with empty string in this case):

class Foo {
  constructor() {
    this.A = "1";
    this.B = "";
    this.C = "3";

    let D = [this.A, this.B, this.C]
      .filter(val => ![undefined, null, ''].includes(val))
      .map(val => ({id: val}));

    console.log(D);
  }
}

new Foo();

Upvotes: 1

Related Questions