我希望能够在对象上生成动态属性,我尝试通过创建一个函数来实现此目的,该函数接受一个输入对象,然后返回一个接受参数的函数。该参数用于设置动态属性。
我的问题是,一旦创建了该函数,我似乎不会每次都获得一个新对象,而是该函数在先前分配的对象上设置该属性。
我曾尝试重新分配对象但无济于事,我已经测试了可行的替代方案(不太理想的代码),但我想知道为什么我的初始解决方案不起作用。
/* 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);
预期产出
{
user_email: { type: 'string', description: 'A user email', required: false }
}
{
user_email: { type: 'string', description: 'A user email', required: true }
}
实际
{
user_email: { type: 'string', description: 'A user email', required: true }
}
{
user_email: { type: 'string', description: 'A user email', required: true }
}
jeck猫
相关分类