why I can't return an object with an added property key in javaScript

Viewed 18

You have been asked to update the visitors list with the amounts that each guest will donate for the organisation . Unfortunately, all the donation amounts found in email messages have been sent to you as strings!

Examples:

trackVisitors({ firstName: "Danciaa", lastName: "fran", age: 21 }, '24'); // should return { firstName: "Danciaa", lastName: "fran", age: 21, paidForTicket: 24 }

1 Answers

If you're fine with mutating the original object, you can do this:

const trackVisitors = (visitor, paidForTicket) => {
  visitor.paidForTicket = +paidForTicket; // or `Number()` or `parseInt()` or various other methods of string->int
  return visitor;
}
console.log(trackVisitors({
  firstName: "Danciaa",
  lastName: "fran",
  age: 21
}, '24'));

If you're making a pure function, you can do this instead:

const trackVisitors = (visitor, paidForTicket) => ({
  ...visitor,
  paidForTicket: +paidForTicket, // or `Number()` or `parseInt()` or various other methods of string->int
});
console.log(trackVisitors({
  firstName: "Danciaa",
  lastName: "fran",
  age: 21
}, '24'));

Related