Reputation: 97
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
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
Reputation: 14927
You could make use of:
Array.filter
to filter out empty and null values, and Array.map
to get the desired format.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