Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript spread operator decision making

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading