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 ?

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

  1. You can Conditionally add properties to an Object with object destructuring

    const obj = {
        ...(key1 && { [key1]: state[key1] }),
        ...(key2 && { [key2]: state[key2] })
    };
    

    If some of the args function is undefined, null or 0 (falsy values) then it will no be added to the object.

    Reply
  2. There is a very scalable way to do it:

    const state= {
      a: "hello",
    
    }
    function getKeysAs (keys) {
    return [...arguments].reduce((acc, cur)=> {
      const newValue = state[cur] && {[cur]: state[cur]}
      return {...acc, ...newValue}
    }, {}) 
    }
    
    console.log(getKeysAs("a", "b"))

    This way, you can pass as much keys as you need without worrying about scalability & undefined values.

    Reply
  3. Assuming you actually mean to do state[key1], not state.key1, here is a solution that doesn’t create superfluous objects:

    const getKeysAs = (...keys) => {
      const result = {};
      for (const key of keys) {
        if (key != null) {
          result[key] = state[key];
        }
      }
      return result;
    }
    
    Reply

Leave a Comment