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.

Kngh2
  • 387
  • 2
  • 4
  • 10

2 Answers2

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

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
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:

KiraLT
  • 2,385
  • 1
  • 24
  • 36