1

I have a list of properties like that:

const firstProperty = this.checkSome(param) ? this.someArray[1] : null;
const secondProperty = this.anotherProperty ? this.anotherProperty.id : null;

Next I want to create an object, which has those properties:

    myObject = {
      firstProperty,
      secondProperty,
};

It works fine, the problem is myObject contains those properties, even when they are null or undefined. What I want is that if, for example, secondProperty is null, then myObject do not have such property after creation, at all. What is the shortest way to achieve that? Consider that amount of properties can be more than two, in fact, I have about a dozen.

2 Answers 2

1

It sounds like you describing an interface with optional properties. So let's start there.

interface MyObject {
    firstProperty?: number
    secondProperty?: string
}

Now you can declare a variable that uses that interface, but missing all optional properties:

const myObject: MyObject = {}

And the last step is to conditionally set those properties on this object:

 if (Math.random() > 0.5) myObject.firstProperty = 123
 if (Math.random() > 0.5) myObject.secondProperty = "a string"

Playground

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

1 Comment

I end up using your way, although the condition for each property doesn't seem right
0

You can loop each property and delete using delete statement:

Object.keys(myObject).forEach(key => {
  if (obj[key] == null) {
    delete obj[key];
  }
})

Or you can use reduce to create a new object:

const newObj = Object.entries(myObjec).reduce((prev, [key, value]) => {
    if (value != null) {
        prev[key] = value
    }
    return prev
}, {} as typeof myObjec)

Note, that the cast is required if you wish to have the same object type.

Related questions:

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.