Search code examples
javascriptdictionaryspread-syntax

Why is my map() with spread syntax not working?


I'm not sure where this is going wrong. I've seen several posts about this specific example from O'Reilly's Learning React, by Banks and Porcello. However, the posts appear to function properly, but my example does not. I don't notice typos. What is the source of my flaw? I'm not sure why I get "HB Woodlawn" instead of a null string value.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
  <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
  
  <script type="text/babel">

    // Editing one object in an array of objects

    let schools = [
      {name: 'Yorktown'},
      {name: 'Stratford'},
      {name: 'Washington & Lee'},
      {name: 'Wakefield'}
    ];

    const editName = (oldName, newName, arr) =>
      arr.map(item => {
        if (item.name === oldName) {
          return {
            ...item,
            name
          }
        }
        else {
          return item
        }
      });

    let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);

    console.log(updatedSchools[1]);  // name: ""
    console.log(schools[1]);  // name: "Stratford"

  </script>
  
</body>
</html>

Solution

  • let schools = [
      {name: 'Yorktown'},
      {name: 'Stratford'},
      {name: 'Washington & Lee'},
      {name: 'Wakefield'}
    ];
    
    const editName = (oldName, newName, arr) =>
      arr.map(item => {
        if (item.name === oldName) {
          return {
            ...item,
            name: newName
          }
        }
        else {
          return item
        }
      });
    
    let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);
    
    console.log(updatedSchools[1]);  // name: ""
    console.log(schools[1]);  // name: "Stratford"
    

    You hadn't added the new value for the name, instead had left it empty. Added name:newName