Reputation: 76
myfunction takes object of a persons as input and returns an a new object contaning first name, last name size and weight of person. If either weight or size was not gven in input object it should not be present in output object
function myFunction(obj) {
return {
fn: obj.fn,
ln: obj.ln,
...(obj.size && { size: `${obj.size}cm` }),
...(obj.weight && { weight: `${obj.weight}kg` }),
};
}
myFunction({ fn: 'Lisa', ln: 'Müller', age: 17, size: 175, weight: 67 })
I can't understand how ...(obj.size && { size:
${obj.size}cm}),
works
Upvotes: 0
Views: 35
Reputation: 6512
This works because of "short circuit evaluation" with the &&
operator.
If the first operand is falsey, nothing will be "spread" into the object literal. If it is not falsey the object { size: ${obj.size}cm
} will be spread into the returned object literal.
Upvotes: 1
Reputation: 33701
You can conditionally create objects with the values (if present), or empty objects (if not present), then (unconditionally) spread them in to the resulting object:
function myFunction(obj) {
const size = obj.size ? { size: `${obj.size}cm` } : {};
const weight = obj.weight ? { weight: `${obj.weight}kg` } : {};
const {fn, ln} = obj;
return {fn, ln, ...size, ...weight};
}
Alternatively (and perhaps a bit less complicated), you can create the result object first, then conditionally set the property values:
function myFunction(obj) {
const {fn, ln} = obj;
const result = {fn, ln};
if (obj.size) result.size = `${obj.size}cm`;
if (obj.weight) result.weight = `${obj.weight}kg`;
return result;
}
Upvotes: 1