Home > database >  Javascript return a NEW object with the key successfully translated
Javascript return a NEW object with the key successfully translated

Time:10-21

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:

{
       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.

CodePudding user response:

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)

CodePudding user response:

Your function translateKey() modifies incoming object. To prevent that, you should create duplicated object, either by {...student} or by Object.assign()

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

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

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

Or a bit dirty way, keep your function as it is and create new object when calling your function (would not recommend)

console.log(translateKey({...student}, "ilsSontMorts", "isDead"));
  • Related