Adding dynamic properties to object only if the name is defined

i have a function like this:

const getKeysAs = (key1, key2) => {
    return {
        [key1]: state.key1,
        [key2]: state.key2
    }
}

So if state.key1 is ‘a’ and state.key2 is ‘b’, calling getKyesAs('one', 'two') would return

{
  one: 'a',
  two: 'b'
}

Now, if one of the argument is undefined, is there a way to not include it in the returned object ?

74 thoughts on “Adding dynamic properties to object only if the name is defined”

Leave a Comment