.map with String.replace function gives me back only one value of the objects

So I want to modify the name of some objects by replacing certain characters with others, in this case (as an example) the letter "g" with "k". Now I want to have back the same array of objects with just one value altered of all objects, the name. But instead of getting back the object array, I only get back all altered values (object.name). I thought with .map(), I can transform an object array and get it back just with the function applied to all objects.

var students = [
    { "number": 4251, "name": "Melissa", "surname": "Giron" },
    { "number": 4321, "name": "Gisele", "surname": "Johnsen" }
]

So this is my example array where I want to change the letter "e" to "z" in all names.

function changeLetterInName(students) {
  return students.map(x => x.name.replace("e", "z"));
}

What I actually want:

[
  { number: 4251, name: 'Mzlissa', surname: 'Giron' }, 
  { number: 4321, name: 'Giszlz', surname: 'Johnsen' }
]

What I get:

['Mzlissa', 'Giszlz']

>Solution :

Yes, that is what Array.prototype.map() does. It replaces every element in your array with the value that is returned from the callback function you are passing to the .map(). Your callback function returns the result of the .replace() that is performed on the name property, so this replaced string will be the new value.

If you don’t care about modifying the original array, you can use a simple Array.prototype.forEach() to iterate over every element, and replace the name.

students.forEach(x => x.name = x.name.replace("e", "z"))

If you want to return a new array instance, so that the original remained untouched (and making changes to the resulting array don’t affect the original), you can use .map(), but you’ll need to return an object that contains all the values like so:

students.map(x => ({...x, name: x.name.replace("e", "z")}))

Working example:

function changeLetterInName(students) {
  return students.map(x => ({ ...x, name: x.name.replace("e", "z") }));
}

var students = [{
    "number": 4251,
    "name": "Melissa",
    "surname": "Giron"
  },
  {
    "number": 4321,
    "name": "Gisele",
    "surname": "Johnsen"
  }
]

console.log(changeLetterInName(students));

Leave a Reply