Search code examples
javascriptobjectecmascript-6

Is there a way to create an object using variables and ignore undefined variables?


I'm trying to find a way of creating an object where upon creation it ignores the values that are undefined.

In the example below, the variable someNames has unknown content when creating the object.

const someNames = {
  catName: 'purry',
  rabbitName: 'floppy',
  turtleName: 'shelly'
};

const { catName, dogName, hamsterName, rabbitName } = someNames;

const animalNames = Object.assign({}, {
  catName,
  dogName,
  hamsterName,
  rabbitName
});

console.log(animalNames);// {catName: 'purry', rabbitName: 'floppy'}

What actually gets logged is this:

{
  catName: 'purry',
  dogName: undefined,
  hamsterName: undefined,
  rabbitName: 'floppy'
}

Solution

  • Don't use Object.assign which copies all own enumerable properties regardless of their value but your own custom function that can filter out undefined properties:

    function assignDefined(target, ...sources) {
        for (const source of sources) {
            for (const key of Object.keys(source)) {
                const val = source[key];
                if (val !== undefined) {
                    target[key] = val;
                }
            }
        }
        return target;
    }
    
    …
    const animalNames = assignDefined({}, {
      catName,
      dogName,
      hamsterName,
      rabbitName
    });