For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array.

For example:

Before - items: ["ball", "book", "pen"]

After - items: ["ball!","book!","pen!"]

const array = [
{
   username: "john",
   team: "red",
   score: 5,
   items: ["ball", "book", "pen"]
 },
 {
   username: "becky",
   team: "blue",
   score: 10,
   items: ["tape", "backpack", "pen"]
 },
 {
   username: "susy",
   team: "red",
   score: 55,
   items: ["ball", "eraser", "pen"]
 },
  {
   username: "tyson",
   team: "green",
   score: 1,
   items: ["book", "pen"]
  },

  ];

This is what I have tried in my JavaScript:

  const PlusItems = array.map(user => user.items+'!');
  console.log(PlusItems);

Answer №1

You can utilize the map function along with destructuring.

const array = [{username: "john",team: "red",score: 5,items: ["ball", "book", "pen"]},{username: "becky",team: "blue",score: 10,items: ["tape", "backpack", "pen"]},{username: "susy",team: "red",score: 55,items: ["ball", "eraser", "pen"]},{username: "tyson",team: "green",score: 1,items: ["book", "pen"]},];
 
let transformedArray = array.map(({items,...rest})=>{
    return {
      ...rest,
       items: items.map( element => element + '!')
    }
})

console.log(transformedArray)

Answer №2

To update the array of strings, you can loop through the input array using the .map() method and utilize Object.assign().

const data = [
  {username: "john", team: "red", score: 5, items: ["ball", "book", "pen"]},
  {username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"]},
  {username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"]},
  {username: "tyson", team: "green", score: 1, items: ["book", "pen"]},
];

const result = data.map(o => Object.assign(o, {items: o.items.map(s => s + "!")}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To solve this, you can utilize the Array#reduce method.

const array = [{username: "john",team: "red",score: 5,items: ["ball", "book", "pen"]},{username: "becky",team: "blue",score: 10,items: ["tape", "backpack", "pen"]},{username: "susy",team: "red",score: 55,items: ["ball", "eraser", "pen"]},{username: "tyson",team: "green",score: 1,items: ["book", "pen"]}];

const transformedArray = array.reduce((accumulator, element) => {
    element['items'] = element['items'].map((item) => `${item}!`);
    accumulator.push(element);
    return accumulator;
}, []);
  
console.log(transformedArray);

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

Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this: [ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":" ...

Exploring how to verify the data type retrieved from PHP using the jQuery post method

Understanding Data Types [{"id":"1","value":"Google"},{"id":"2","value":"Samsung"}] In programming, it's crucial to correctly identify the type of data you are working with. To help with this, I have created a custom function that determines the typ ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

Issue with Mongoose $in operator causing updates to only affect a single document

Having some issues with the "$in" operator in Mongoose. I have a User schema that includes an array of Card schema. The Card schema contains a 'score' field that I want to update based on a list of Card ids. Here's what I have attempted: Us ...

ReactJS Modal popping up repeatedly while inside a loop

Hey there, I've been experimenting with ReactJS and came across this amazing Modal Component for opening videos in a modal. However, I encountered an issue when placing the Modal inside a loop with multiple links - it opens multiple times correspondin ...

What could be causing the $httpProvider.interceptors to unexpectedly return an 'undefined' value?

Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors. This is the structure of my app: var app = angular.module("restaurantList", []); The yelpAPI service handles authenticatio ...

Fetching images from directory in xcode

I'm encountering difficulties loading images from a file into an array. I've tried different methods found online but still haven't found a solution. Being new to objective-c and a bit rusty on the rest, I could really use some guidance. In ...

Is there a way to have text appear in a popup when I reach it while scrolling?

Is there a way to make the textblocks on my website increase in size or pop up when I scroll down to them? I've attempted to search for a solution online but have been unsuccessful in finding one. ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

Simple steps to change the appearance of the delete button from an ajax button to an html button

I need help transitioning the delete button from an ajax button to an html button in my code. Currently, the delete button functions using ajax/javascript and when clicked, a modal window pops up asking for confirmation before deleting the vote. However, ...

Hiding Div with JavaScript (Quick and Easy)

Hey there, I'm looking to make regStart and regPage alternate visibility based on a click event. I'm still getting the hang of JavaScript so any simple answers would be appreciated. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/x ...

When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is ...

Ways to divide a cluster in three.js?

My dilemma involves voxels that require grouping, so I have opted to place them in a container: container.add(e); Next, I integrate the container into the scene. However, I am now faced with the challenge of how to separate the voxels without the need to ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Double trouble: Knockout validation errors displayed twice

Currently, I am using the knockout validation plugin to validate a basic form field. The validation functionality is working as expected, however, it seems to be displaying the same error message twice under the text box. The code snippet that I am using ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach: Retrieve data based on username and password using $http.get Store the result in $scope.getResult=res; Assign variables to the retrieved data: var result=$scope.getResult ...