Modify an object's attribute value by utilizing the map function in ES6

In my ES6 coding endeavors, I am striving for a specific outcome. Imagine I have an array of objects titled schools.

let schools = [
    {name: 'YorkTown', country: 'Spain'},
    {name: 'Stanford', country: 'USA'},
    {name: 'Gymnasium Achern', country: 'Germany'}
];

My goal is to create a function called editSchoolName that will accept 3 parameters: schools (the predefined array), oldName, and name.

The oldName parameter will contain the current name of the school that needs to be updated with the value passed in the name parameter.

To maintain the original state of the schools variable, I plan to utilize a map function that will generate a new array with the desired modifications.

The editSchoolName function will be invoked as follows -

var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");

In this case, the name YorkTown should be substituted with New Gen. Therefore, the resulting array updatedSchools should appear as -

let updatedSchools = [
    {name: 'New Gen', country: 'Spain'},
    {name: 'Stanford', country: 'USA'},
    {name: 'Gymnasium Achern', country: 'Germany'}
];

This is how the editSchoolName function is structured -

const editSchoolName = (schools, oldName, name) =>
    schools.map(item => {
        if (item.name === oldName) {
          /* This is the section where the logic needs to be applied */
        } else {
          return item;
        }
    });

I need assistance in modifying the editSchoolName function to achieve the desired outcome as described above.

Answer №1

Give this a shot, use ES6 and the Object.assign() method to duplicate array elements and update a new object.

let schools = [{
        name: 'YorkTown',
        country: 'Spain'
    },
    {
        name: 'Stanford',
        country: 'USA'
    },
    {
        name: 'Gymnasium Achern',
        country: 'Germany'
    }
];

const editSchoolName = (schools, oldName, name) => {
    return schools.map(item => {
        var temp = Object.assign({}, item);
        if (temp.name === oldName) {
            temp.name = name;
        }
        return temp;
    });
}

var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
console.log(updatedSchools);
console.log(schools);

Utilizing destructuring

const schools = [
  {
    name: "YorkTown",
    country: "Spain",
  },
  {
    name: "Stanford",
    country: "USA",
  },
  {
    name: "Gymnasium Achern",
    country: "Germany",
  },
];
const editSchoolName = (schools, oldName, newName) =>
  schools.map(({ name, ...school }) => ({
    ...school,
    name: oldName === name ? newName : name,
  }));
const updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
console.log(updatedSchools);

Answer №2

To obtain the modified object, you must follow these instructions:

const modifySchoolName = (schoolList, prevName, updatedName) =>
  schoolList.map(entry => {
      if (entry.name === prevName) {
        return {...entry, updatedName};
      } else {
        return entry;
      }
});

Answer №3


   const updateSchoolName = (schools, currentName, newName) =>
    schools.map(({name, ...school }) => ({ ...school, name: currentName === name ? newName : name }));

Utilizing a ternary operator can help simplify the code.

Answer №4

It's surprising that none of the responses offer a straightforward solution

function updateSchoolName(schools, oldName, newName) {
      return schools.map(school => {
            if (school.name === oldName) {
                  school.name = newName;
            }
            return school; 
      });
}

Answer №5

If you're looking to make changes specifically to the commented section:

function updateSchoolName(schools, oldName, newName) {
    return schools.map(item => {
        if (item.name === oldName) {
            let updatedItem = Object.assign({}, item);
            updatedItem.name = newName;
            return updatedItem;
        } else {
            return item;
        }
    });
}

Answer №6

it's as easy as pie:

function modifySchoolName(schools, prevName, newName) {
    let modifiedList = schools.map((item, index) => {
        if (item.name === prevName) {
            let updatedItem = { ...item, name: newName };
            return updatedItem;
        } else {
            return item;
        }
    });
    return modifiedList;
}

Answer №7

let universities = [{
    name: 'Harvard',
    country: 'USA'
  },
  {
    name: 'Oxford',
    country: 'UK'
  },
  {
    name: 'Sorbonne',
    country: 'France'
  }
];

let updatedUniversities = [{
    name: 'New Age',
    country: 'USA'
  },
  {
    name: 'Oxford',
    country: 'UK'
  },
  {
    name: 'Sorbonne',
    country: 'France'
  }
];

const editUniversityName = ((universities, oldName, name) =>{
  universities.map(item => {
    if (item.name === oldName) {
      item.name = name;
      return item.name;
    } else {
      return item;
    }
  });
  console.log(universities);
});

editUniversityName(universities, 'Harvard', "New Age");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

Determine the size of an SVG while taking into consideration any strokes applied

Is there a way to seamlessly position an SVG in the corner of a div, despite having a dynamically generated stroke? Calculating the distance to the outermost part of the border proves difficult when dealing with irregular shapes like stars. Here's my ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Can a jQuery object be generated from any random HTML string? For example, is it possible to create a new link variable like this: var $newlink = $('<a>new link</a>')?

I'm looking to create an object without it being attached to the dom. By passing a HTML string, I want to insert the element into the dom and still have a reference to it. ...

Storing an Array in JSON Format to a File with PHP

{"Files": [ {"file_name": "Text_file.txt","path": "to_folder","file_id": "abc12345"}, {"file_name": "Img.jpg","path": "to_folder" ...

Reset filter when the "All" option is chosen in Vue.js

There is an array of objects that looks like this: obj= [{name: 'joe', job: 'teacher', city: 'miami'}, {name: 'bill', job: 'police', city: 'yorkshire'}, {name: 'sarah', job: 'driver ...

How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as n ...

How can I use regular expressions to validate one-letter domain names?

I am in the process of developing a validation rule for my C# MVC Model using Regex. [RegularExpression(@"(\w[-._+\w]*\w@\w{1,}.\w{2,3})", ErrorMessage = "* Email Address: Please enter a valid Email Address.")] public virtual stri ...

NextJs manages the logic for processing requests both before and after they are handled

NextJs stands out from other frameworks due to its lack of support for filter chains, request pre-processing, and post-processing. Many node project developers or library creators may find these features essential for executing logic before and after API c ...

Array of Typed Objects in TypeScript

Here is the setter I created in TypeScript: public set data(data: Array<Data>) { console.log(data[0].getterProperty); console.log(data[0] instanceof Data); console.log(typeof data[0]); this.setGridDataIfReady(); } If data contains only one ...

I am just starting to explore firebase and I'm having trouble organizing my data. I've attempted to use the query function and orderBy

After experimenting with query and orderBy() methods, I'm still struggling to properly integrate it into my code. Here's what I have so far: Methods: async saveMessage(){ try { const docRef = await addDoc(collection(db, "chat"), ...

The unusual interactions between JavaScript and QML

Encountering strange behavior with JavaScript. I am currently working on a basic example application using QT-QML and JavaScript. Within this application, I have implemented HTTP Requests triggered by a button that sends the request through JavaScript. ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

Breaking free from JavaScript snippet within a PHP function in WordPress

There seems to be an issue with a function within one of the PHP files on a WordPress website. It appears that there may be an error related to escaping multiple quotes and slashes. Here is the specific line of code causing trouble: echo '<script ...

Loading templates (partials) in Angular.js on the fly

Is there a way to dynamically load templates into an Angular app based on a parameter within a ng-foreach loop? <body ng-app="MyApp" ng-controller="ExampleController as example"> <div ng-repeat="item in example.items" class="someClass" ng-swi ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Create a constructor that takes in inputs and adds them to an array

My current challenge involves working with a class that has a constructor and utilizing it within an array. Unfortunately, when attempting to do so, I encounter an error. Here is the snippet of code in question: using System; class ClassA { public ...

API call to frontend is not displaying complete properties of the returned object

I've run into a bit of an unusual issue. Currently, I am sending an AJAX request to my backend API. The API itself is quite straightforward and simply returns an array of objects like so.... API: [HttpGet()] public IActionResult Get() { ...

Interactive HTML and PHP form designed to compute and display the result of a straightforward mathematical equation

I'm looking to add a dynamic HTML/php form on my webpage that can solve the following formula instantly without any page refresh. I am confused about the best approach and the code required to make it happen. The formula I want to implement is as fol ...