I want to be able to generate a dynamic property on objects and I have tried doing this by creating a function that takes an input object to then return a function that takes a parameter. This parameter is used to set the dynamic property.
My issue is that once the function is created, I don't seem to be getting a new object each time and instead the function is setting the property on a previously assigned object.
I have tried re-working the assigning of an object but to no avail, I have tested out alternative (less ideal code) which works but I want to know why my initial solution does not work.
/* Returns a function which will assign a 'required' property to all objects within the given object */
const generateSchemaField = obj => {
obj = Object.assign({}, obj);
return function(required = false) {
Object.keys(obj).forEach(key => {
Object.assign(obj[key], {
required,
});
});
return obj;
};
};
/* The way the above function would be invoked*/
const userEmailUsingGenerateSchemaField = generateSchemaField({
user_email: {
type: 'string',
description: 'A user email',
},
});
/* The below function does not encounter the same problem */
const userEmailNotUsingGenerateSchemaField = function(required = false) {
let obj = {
user_email: {
type: 'string',
description: 'A user email',
},
};
Object.keys(obj).forEach(key => {
Object.assign(obj[key], {
required,
});
});
return obj;
};
let firstResultUsing = userEmailUsingGenerateSchemaField();
let secondResultUsing = userEmailUsingGenerateSchemaField(true);
console.log(firstResultUsing);
console.log(secondResultUsing);
Expected Output
{
user_email: { type: 'string', description: 'A user email', required: false }
}
{
user_email: { type: 'string', description: 'A user email', required: true }
}
Actual
{
user_email: { type: 'string', description: 'A user email', required: true }
}
{
user_email: { type: 'string', description: 'A user email', required: true }
}