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
>Solution :
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;
}