2

I'm using const in a function to define a few variables as follows

const printBlock.format({
  name : this.matchedData.clientName,
  date : this.matchedData.jobDate,
  destination : this.matchedData.address,
  apartment : this.matchedData.address2,
  stateZip : this.matchedData.zipcode
})

From then, I'm printing out all of these things in order that they're declared. However, some of the data doesn't have an apartment number so it'll show up as:

John Doe

6/6/2018

135 Testdemo Avenue

null

NY 11111

Is it possible to use an if function within declaring the consts in order to make it so that:

if (this.matchedData.address2 == null){
//Do nothing
} else {
apartment : this.matchedData.address2,
}
1
  • 5
    const printBlock({…}) is a syntax error. What are you actually doing? Commented Jun 6, 2018 at 19:50

4 Answers 4

3

No, but you can use a ternary

var object = {
  address: '1111',
  apartment : this.matchedData.address2 ? "" : this.matchedData.address2
}
Sign up to request clarification or add additional context in comments.

2 Comments

This approach will also create a property even if it's null
This is the solution that worked for me! I ended up formatting as follows: apartment : ((this.matchedData.address2 !== null) ? this.matchedData.address2 : ' ')
1

You could use Object.assign and check with property and if not null, take an object for assignment.

printBlock(Object.assign(
    {
        name: this.matchedData.clientName,
        date: this.matchedData.jobDate,
        destination: this.matchedData.address,
        apartment: this.matchedData.address2,
        stateZip: this.matchedData.zipcode
    }, 
    this.matchedData.address2 === null || { apartment: this.matchedData.address2 }    
));

Comments

1

You can create your object first without the apartment entry and then add the apartment entry if it is not null...

const a = {
  name : this.matchedData.clientName,
  date : this.matchedData.jobDate,
  destination : this.matchedData.address,
  stateZip : this.matchedData.zipcode
};

if (this.matchedData.address2 !== null){
  a.apartment : this.matchedData.address2;
}

Comments

0

const printBlock({...}) will throw an error because it isn't a valid way to initialize a constant. If printBlock is a function, why not handle null values in the body of printBlock?

function printBlock(obj) {
    for (var prop in obj) {
        if (obj[prop]) {
            console.log(obj[prop]); // or do whatever you mean by 'print'
        }
    }
}

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.