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 return a NEW object with the key successfully translated

trying to solve this problem:
This function will take an object representing a student’s data, a key that needs changing, and its English translation.

and so far I managed to solve it with this code:

function translateKey(student, keyToChange, translation) {
  student[translation] = student[keyToChange];
  delete student[keyToChange];
  return student;
}

const student = {
  firstName: "Napoleon",
  surname: "Bonaparte",
  ilsSontMorts: true,
};

console.log(translateKey(student, "ilsSontMorts", "isDead"));

but the second request is to return these changes into a NEW OBJECT, with the key successfully translated E.g:

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

{
       firstName: "Napoleon",
       surname: "Bonaparte",
       isDead: true,'
    }

I tried different "solutions" like

return new Object(student)

but it doesn’t work.. how can I return my results as new object?

thank you for your support.

>Solution :

You can refer below solution

function translateKey(student, keyToChange, translation) {
const newObj = {...student}
  newObj[translation] = newObj[keyToChange];
  delete newObj[keyToChange];
  return newObj;
}

const student = {
  firstName: "Napoleon",
  surname: "Bonaparte",
  ilsSontMorts: true,
};


console.log('new Object',translateKey(student, "ilsSontMorts", "isDead"));
console.log('oldObject',student)
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