Task within a mapping function?

I am facing an issue with the following code snippet:

this.array1 = this.array1.map(a => (a.name = "Harold"));

It seems like there is a syntax error, and I can't figure out why. My intention is to set the "name" property of every object in array1 to Harold.

The structure of the array is as follows:

array1 = [
    {
        name: "ashley",
        last: "bob"
    },
    {
        name: "tiny",
        last: "tot"
    }
]

The error message I receive is:

Arrow function should not return assignment

The desired outcome is an array that looks like:

array1 = [
    {
        name: "Harold",
        last: "bob"
    },
    {
        name: "Harold",
        last: "tot"
    }
]

Answer №1

One way to update objects without mutating the original data is to spread the object and assign a new name.

This methodology ensures that the given data remains unchanged.

const
     array1 = [{ name: "ashley", last: "bob" }, { name: "tiny", last: "tot" }],
     array2 = array1.map(object => ({ ...object, name: "Harold" }));

console.log(array2);

Answer №2

Avoid returning assignments in arrow functions

When constructing an [arrow function], be cautious of inadvertently returning the contents within the brackets, which may result in an assignment operation. Take a look at the initial demonstration on this site.

this.array1 = this.array1.map(a => (a.name = "Harold"));

The function of map requires explicit return of the desired object as an element in your Array. In the following code snippet, I am explicitly returning 'a'.

this.array1 = this.array1.map(a => {
a.name = "Harold";
return a;});

It is important to note that instead of using map, it is recommended to utilize forEach. According to the documentation, map generates a new array by calling a specified function on each element in the original array.

Answer №3

Using Array.prototype.map allows for the creation of a new array by taking the original array as input and replacing each item in the array within the callback function.

If you want to assign a value without explicitly returning anything in your callback, consider utilizing the comma operator to return the same object after mutation:

this.array1 = this.array1.map(a => (a.name = "Harold", a));

Here is a snippet showcasing this approach:

const array1 = [{name: "ashley", last: "bob"}, {name: "tiny", last: "tot"}];

const array2 = array1.map(a => (a.name = "Harold", a));

console.log(array2);

Note: It's generally advised not to use map to mutate the original array. Instead, consider using forEach to mutate objects within the array or return a new array without mutating the original one. By following this recommendation, you prevent ending up with a second array containing the same mutated objects from the first array.

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

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

How can I spin the entire canvas in React JS using react-three-fiber?

I recently followed a tutorial from Codrops on creating a scrollable site using react-three-fiber. However, I made some changes like centering all the items and removing the RGB split effect. Now, I want to achieve a diagonal scroll effect by rotating the ...

Show the information obtained from the dropdown menu selection

Upon selecting a different item from the drop-down list, I want the specific data related to that field from the MySQL database to be displayed. Currently, I am able to retrieve the value of the selected item in the dropdown menu but encountering difficul ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

Struggling to display filtered content in React using State

As a newcomer to React, I am working on a todo list that shows both current and completed tasks using LocalStorage. Each task has a boolean property called "active" which is toggled when a user clicks on the task checkbox. I have a filter in place to separ ...

Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this: <div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" :value="item.title"> </div> ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

The success function in Ajax jQuery isn't being triggered even though the code is running

When using AJAX, I am trying to pass a json variable. Here is the ajax function I have: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> function emailCheckForFrontend() { var key='7 ...

Using linear-gradient() in the border-image property does not actually generate a border

I am attempting to add a linear gradient border around a dynamically created div using JavaScript. However, I am not seeing the border show up as expected and it is not displaying in black. Check out my code snippet below: const devlogList = document.cre ...

Utilizing SequelizeJS to Pass an Array of Values

I am currently exploring the possibility of passing an array as the value for the property of an instance. In my model, I have set the dataType to STRING and I am inserting values from jQuery fields into an array which I then parse from the body and assign ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

Struggling to get a package running in Next.js that is functioning perfectly in ReactJS

Link I have integrated the JSME React npm package into my application to utilize the JSME editor. While this package works seamlessly in a ReactJS environment, I am encountering issues when trying to use it in a Next.js project. I am receiving an error mes ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

Ways to design a vertical tab using CSS and JavaScript

I am currently working on creating a Vertical tab element using CSS and jQuery. However, I am facing an issue where I need to display the content of the first tab upon page load. I have tried using the following line of code but it does not seem to be work ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Angular 2 iframe balked at being shown

Whenever I enter a URL into a text input and press enter, my objective is to have the URL open in an iframe. However, some websites produce an error when trying to do so. Is there a method to successfully display a web page in an iframe? Error message: Th ...

A basic Vue component shows error message "SyntaxError: import not found: default"

I seem to be facing an issue while breaking down some large components into smaller ones. One of the new components I created appears mostly empty: <div> test </div> <script> export default { data() {} } </script> In my ...

Detecting changes in AngularJs elements

Below is the code snippet provided: handleFileSelect = (evt) -> console.log(1) file = evt.currentTarget.files[0] reader = new FileReader() reader.onload = (evt) -> $scope.$apply ($scope) -> $scope.myImage = evt.tar ...