-1

So I have been given a question below...

function translateKey(student, keyToChange, translation) {  }

/*
This function will take an object representing a student's data, a key that needs changing, and its English translation.  
E.g. 
const student = {
  prénom: 'Carla',
  surname: 'Bruni',
  job: 'Artist'
}
const keyToChange = 'prénom'
const translation = 'firstName'

It returns a **new object** with the key successfully translated into English.
E.g. 
{
  firstName: 'Carla',
  surname: 'Bruni,
  job: 'Artist'
}
*/

I have started off with ...

function translateKey(student, keyToChange, translation) {

const translated = {keyToChange : translation};

const newObject = {};


// not really sure where to go from here, help please!
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
newtojs
  • 31
  • 3

2 Answers2

0

Since your objectif is to rename an object key you can start looking at this question who has very good answers.
And you can take the answer of ChaosPandion as example and maybe do it like this :

function translateKey(student, keyToChange, translation) {
    var newObject = Object.assign({}, student);
    // Do nothing if the names are the same
    if (keyToChange === translation) {
        return newObject;
    }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (newObject.hasOwnProperty(keyToChange)) {
        newObject[translation] = newObject[keyToChange];
        delete newObject[keyToChange];
    }
    return newObject;
}

If it's an exercice you had to do for a class please read the other question I linked to see others ways and try to properly understand the solution, for example why it's important to check hasOwnProperty or why we use === instead of simply ==.

Ben Souchet
  • 1,450
  • 6
  • 20
  • thank you BSO, but for some reason I am getting an error as I need to return a new object... AssertionError: expected { Object (prénom, surname, ...) } to not equal { Object (prénom, surname, ...) } – newtojs Dec 07 '19 at 23:07
  • @newtojs I edited my answer, now the function return a new object :) – Ben Souchet Dec 07 '19 at 23:12
  • thank you so much I have been working on this one for the past day and got no where!!! – newtojs Dec 07 '19 at 23:25
  • @newtojs Happy to help, if you think this answer solve your issue you can [accept the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – Ben Souchet Dec 07 '19 at 23:37
0
if (old_key !== new_key) {
  Object.defineProperty(o, new_key,
    Object.getOwnPropertyDescriptor(o, old_key));
  delete o[old_key];
}

From this answer:

https://stackoverflow.com/a/14592469/9504351

  • I am getting the following error as i need to return a new object, any hints on how to do this please? Thanks AssertionError: expected { Object (surname, job, ...) } to not equal { Object (surname, job, ...) } – newtojs Dec 07 '19 at 23:18