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

Run the setInterval function immediately on the first iteration without any delay

Is there a way to display the value immediately the first time? I want to retrieve the value without delay on the first load and then refresh it in the background. <script> function ajax() { ...

Unable to open modal using a button in PHP

<?php $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($result)) { echo '<tr><td>'; echo '<h5 style="margin-left:6px; color:black;">' . $row['id'] . '</h5> ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Ways to extend the timeout duration for Vercel Serverless functions

I've encountered an issue with my API endpoint on a NextJS project where it exceeds the 60-second time limit to execute. Despite being on a pro Vercel plan, I have been unable to extend the timeout limit successfully. Within the endpoint itself, I at ...

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

Display array values in JavaScript from different arrays

I'm currently working on extracting data from my API to plot it in a graph. Specifically, I am interested in obtaining an array that contains only the 'date' values. Here's what I have managed to extract so far: This is the code snippe ...

How can we activate navigation on a mobile browser?

I am currently working on a small HTML5/JavaScript website designed to be accessed by mobile browsers on devices such as Android and iPhone. I am utilizing the geolocation feature of HTML5 to obtain the user's current location, but my goal is to then ...

Fixing the issue with animated scrolling in React Native's Flatlist component

I attempted to customize the default refresh indicator for a Flatlist in React Native. My goal was to create something similar to Snapchat, Instagram, or the default iOS refresh indicator instead of the unattractive Android indicator. This is what I tried: ...

Creating a hover effect for a div in jQuery or CSS: Keeping the div visible even when hovered

I have two divs in my layout: one is titled "title" and the other is called "description". I successfully made the description div appear when hovering over the title div. You can see an example of this behavior in action on this fiddle Now, I want to cha ...

Which is quicker: loading JSON via Ajax or loading the entire output through Ajax?

I'm interested in gathering different perspectives on this topic. Currently, I have Jquery initiating a function through ajax which loads data in two ways: The ajax script fetches JSON data from the server itself, then utilizes JavaScript to pars ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

I'm having trouble finding the issue in this straightforward code snippet. Can someone pinpoint the error for

(server-side) const express = require('express'); //setting up app instance const app = express(); //middleware const bodyParser = require('body-parser'); app.use(express.urlencoded({extended: false})); app.use(express.json()); //imple ...

Unable to Achieve Full Height with Vuetify Container

Challenge: I'm facing an issue with my <v-container> component not consistently spanning the entire height of the application. Despite trying various methods such as using the fill-height property, setting height: 100%;, height: 100vh;, and expe ...

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

JavaScript having trouble parsing JSON, despite Chrome console being able to parse it flawlessly

I've hit a roadblock while attempting to retrieve coordinates from a database for the Google Maps API in order to create a polygon. First, I fetch my data from the database using Laravel Framework: MapController - public function getallmapcoords(re ...

The combination of Grunt and Babel runs smoothly, but fails to produce any results

I'm fairly new to the world of grunt and npm. After diving into the documentation, I managed to create my own package.json and a Gruntfile.js. This is how my directory structure looks: / |- src |- myfile.es6 |- anotherfile.es6 |- etc. |- ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...