Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
}
like image 824
silverlight513 Avatar asked Sep 15 '16 14:09

silverlight513


2 Answers

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
});
like image 119
Bergi Avatar answered Nov 15 '22 11:11

Bergi


You could do something like this just to clean those properties

Object.keys(animalNames).forEach(function (key) {
    if(animalNames[key] === undefined) delete animalNames[key];
});
like image 26
taguenizy Avatar answered Nov 15 '22 12:11

taguenizy