skip to Main Content

The task I have is:

The makeGuestList function takes an object with a name property whose value will be a string consisting of a first name and a last name, separated by a space. The function should return an object.

The function should remove the name property, replace it with firstName and lastName properties, as shown in the examples below:

makeGuestList({ name: "Hannah Fry", age: 46 });
// should return { firstName: "Hannah", lastName: "Fry", age: 46 }

My code is thus:

function makeGuestList(person) {
    const [firstName, lastName] = person.name.split(" ");
    return { "firstName": firstName, "lastName": lastName };
}

const guest = { name: "Ada Lovelace" };
console.log(makeGuestList(guest));

When I run the code I get the error message:

All other properties on the object are unchanged
✕ AssertionError: expected { firstName: 'Ada', …(1) } to deeply equal { firstName: 'Ada', …(3) }

2

Answers


  1. In your current implementation, you’re only returning an object with firstName and lastName, and all other properties from the original object are not included in the returned object.

    To fix this, you can use the spread operator ... to include all properties from the original object in the returned object.

    function makeGuestList(person) {
      const { name, ...rest } = person;
      const [firstName, lastName] = name.split(" ");
      return { firstName, lastName, ...rest };
    }
    const guest = { name: "Ada Lovelace", age: 36 };
    console.log(makeGuestList(guest));
    Login or Signup to reply.
  2. As an alternative to ... spread operator, you can also use the delete keyword to mutate the original person object argument by adding firstName and lastName property, and then remove name property:

    function makeGuestList(person) {
      const [firstName, lastName] = person.name.split(' ');
      person.firstName = firstName; // add new property 'firstName' to person
      person.lastName = lastName; // add new property 'lastName' to person 
    
      delete person.name; // remove `name` property
    
      return person;
    }
    
    const guest = { name: "Ada Lovelace", age: 46 };
    console.log(makeGuestList(guest));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search