I'm dealing with multiple (about 10) if clauses, each clause targeting a different object property ... something like shown with the next provided example code ...
if (typeof credentials.useraa !== 'undefined') {
data.useraa = credentials.useraa
}
if (typeof credentials.userac !== 'undefined') {
data.userac = credentials.userac
}
if (typeof credentials.userad !== 'undefined') {
data.userad = credentials.userad
}
How can one achieve the same result with less repeating code in a shorter (and maybe more generic/expressive) way, like combining the if clauses into a single one if that was a possible approach to start with.
A maybe already obvious approach was to iterate an array of property names / keys and assign only the property values of credentials (source object) as entries (key-value pairs) to data (target object) which are not undefined.
One can take this approach one step further and implement it as a reusable function by taking advantage of the thisArg parameter which almost every array method does support.
An implementation then might look like the next provided example code ...
function assignDefinedValueToBoundTarget(key) {
const { source, target } = this;
const value = source[key];
if (typeof value !== 'undefined') {
target[key] = value;
}
}
const credentials = {
useraa: 'userAa',
// userab: 'userAb',
userac: 'userAc',
userad: 'userAd',
};
const data = {};
console.log({ data });
['useraa', 'userab', 'userac', 'userad']
.forEach(assignDefinedValueToBoundTarget, {
source: credentials,
target: data
});
console.log({ data });
.as-console-wrapper { min-height: 100%!important; top: 0; }
... or in terms of "defined equals an own property" regardless of the actual property value ...
function assignOwnPropertyValueToBoundTarget(key) {
const { source, target } = this;
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
const credentials = {
useraa: 'userAa',
userab: undefined,
userac: 'userAc',
userad: null,
};
const data = {};
console.log({ data });
['useraa', 'userab', 'userac', 'userad', 'userae']
.forEach(assignOwnPropertyValueToBoundTarget, {
source: credentials,
target: data
});
console.log({ data });
.as-console-wrapper { min-height: 100%!important; top: 0; }