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'
}
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
});
You could do something like this just to clean those properties
Object.keys(animalNames).forEach(function (key) {
if(animalNames[key] === undefined) delete animalNames[key];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With