I have a variable name
and I want to add it to an object only if it's defined and not null
. For example, I check the value of name
:
let name = null;
if(nameExists) {
name = 'John Smith';
}
Then I only want to add it to the object as a field if it exists and is not null.
const results = {
title: $(el).find('.title').text(),
name
};
But this doesn't work. Any ideas?
CodePudding user response:
I hope this example clears your concept.
function addName(name) {
let obj = {"site":"stackoverflow"}; // create an object)=(it may be pre-existing)
if(name) {
obj = {...obj, name}; // add name field to obj only if it exists
}
return obj;
}
const ex1 = addName();
const ex2 = addName('John Smith');
console.log('If name is null: ', ex1);
console.log('If name exists: ', ex2);
CodePudding user response:
Well, to do that, you have to spread an object containing the property or an empty object, depending on whether you want to add the property:
const results = {
title: $(el).find('.title').text(),
...(
name !== null
? {name}
: {}
)
};
But I think a conditional assignment could be clearer:
const results = {
title: $(el).find('.title').text()
};
if(name !== null)
results.name = name