0

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']
Ivar
  • 6,138
  • 12
  • 49
  • 61

2 Answers2

0

You are correctly using the .map() method to iterate through each object in the students array and replacing the letter "e" with "z" in the name property. However, you are only returning the modified name property and not the entire object. This function replaces the name property of x, but returns the whole x, not just name.

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

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));
Ivar
  • 6,138
  • 12
  • 49
  • 61