i was trying to solve this problem in javascript : Write a function that takes an object as argument containing properties with personal information .Extract firstName, lastName, size, and weight if available .If size or weight is given transform the value to a string .Attach the unit cm to the size .Attach the unit kg to the weight .Return a new object with all available properties that we are interested in .So i gave this solution :
function myFunction(obj) {
const {fn:fn , ln:ln ,size:s ,weight:w}= obj;
var newObj= {fn:fn , ln:ln};
if (s!==undefined && w!==undefined){
newObj={fn:fn , ln:ln ,size:s.toString()+'cm' ,weight:w.toString()+'kg'};
}
else if(s===undefined || w===undefined){
if (s===undefined && w!==undefined){
newObj={fn:fn , ln:ln ,weight:w.toString()+'kg'};
}
else if (s!==undefined && w===undefined) {
newObj={fn:fn , ln:ln ,size:s.toString()+'cm'};
}
}
return newObj
}
And the author's solution was :
function myFunction(obj) {
return {
fn: obj.fn,
ln: obj.ln,
...(obj.size && { size: `${obj.size}cm` }),
...(obj.weight && { weight: `${obj.weight}kg` }),
};
}
Can someone explain to me (or refer me to where i can find the answer) the lines with the spread operator and why does that work when the value of weight or size is undefined ? Thank you