Use a conditional statement for each element within the array

Below is the code I am currently using:

if (res[0].toString() == "hello") { res[0] = "string"; };

While it works, I would like this logic to apply to all elements rather than just the first one.

Is there a way to achieve this for every element in the array?

Edit: This issue has been resolved. Thank you everyone for your help!

Answer №1

One option is to update a mapped value.

result = result.map(obj => obj === "hello" ? "text" : obj);

Answer №2

 res = res.map(item => item === "hello" ? "string" : item);

or

for(const [index, val] of res.entries())
 if(val === "hello") res[index] = "string";

Avoid unnecessary use of .toString() (assuming it's already a string) and stick to using === over ==, unless there is a specific reason for using the latter (which is rare)

Answer №3

That is an example of using the .map method.

const arr = [
  'hello',
  'World',
  'Hello',
  8,
];
arr2 = arr.map((el) => {
  if(el.toString() === 'hello') return 'string';
  return el;  // keep the original value unchanged
});
console.log(arr2);

This code snippet will give the following output:

[ 'string', 'World', 'Hello', 8 ]

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

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

Retrieve every hour between two specific timestamps

I am attempting to retrieve all dates between two timestamps that fall on a specific day of the week. I have a start date represented by 'start1' and an end date represented by 'end1'. Additionally, I have a list of days with correspon ...

Rendering Next.js app within HTML markup provided as a string

I am facing a challenge with integrating my Next.js app into an external HTML markup. The provided markup structure consists of the following files: header.txt <html> <head> <title>Some title</title> </head> < ...

Navigating to a particular value in Vue: A step-by-step guide

In my Vue application, I have a basic table structure: <tbody> <tr v-for="(item, index) in items"> <td> ... </td> </tr> </tbody> The items are dynamically added using the unsh ...

Ember.js alternative for Angular's filter for searching through ng-models

Looking for an easy way to implement a search filter similar to Angular? <input type="text" ng-model="resultFilter" placeholder="Search"> <ul> <li ng-repeat="result in results | filter:resultFilter">{{result.name}}</li> </u ...

Combining PouchDB with Vue.js for seamless integration

Has anyone successfully integrated PouchDB / vue-pouch-db into a Vue.js application before? I encountered an error when attempting to define the PouchDB database. Here are the definitions I tried: import PouchDB from 'pouchDB' or import PouchDB ...

Developing Functions using MongoDB Console

When running the query db.graduates.find({student_id: '2010-01016'}).pretty(), it returns a result. Afterwards, I created a function: function findStud(name,value){ return db.graduates.find({name:value}); } However, while executing findStud("s ...

Combining Multidimensional Array with Matching Key Using PHP

I've been grappling with this specific problem over the past few days. While I have searched through StackOverflow, I have only found solutions that assume all keys in the multidimensional array are identical. My challenge involves merging a multidim ...

Managing data from two tables in Node.js with ejs

I have a question regarding my node.js project that I need help with. As a beginner in this field, I believe the answer may be simpler than anticipated. In my code file named index.js, I found the following snippet after referring to some online documenta ...

Creating beautiful user interfaces with Material UI and React

I'm currently exploring how to integrate Material UI into my React project. After successfully installing the module, I attempted to create a custom button component. Here is my Button.js file: import React from 'react'; import FlatButton ...

Endless loop in React Native with an array of objects using the useEffect hook

For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component. To tackle this issue, I have initialized a local state as follows: const [myState, setMyState] = useS ...

"Upon inspection, the TrackerReact Container shows that the user's profile.avatar is set, yet the console is indicating that

Within my app, I designed a TrackerReact container named ProfileSettingsContainer. This container retrieves the user data with Meteor.user() and passes it to a function called user(), then sends this information to the ProfileSettings component. The main o ...

When trying to bind an object that is constantly changing, one-way binding may not effectively capture those dynamic modifications

For a detailed review of the code, please check out the plnkr. I am quite new to AngularJS components. I have created two simple AngularJS components with the exact same bindings: bindings: { value:'@', field:'@', object: '<&a ...

Success function in AJAX triggered when no JSON data is returned

Despite its simplicity, I'm having trouble getting this right. I'm utilizing jQuery/AJAX to fetch data (in the form of JSON) from my database. Upon successful retrieval, I have a function to display the data. While this works as expected, I now a ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

Trigger JavaScript function once all Ajax requests have completed

Seeking assistance with troubleshooting JavaScript code that is not functioning as expected. The Application sends file names to the server via Ajax calls for processing, but I need to update the database once all imports are complete. The problem arises ...

"NodeJS Express: The intricacies of managing overlapping routers

While constructing a NodeJS express API, I have encountered a peculiar bug. It seems that some of the endpoints are overlapping, causing them to become unreachable as the request never completes and ends up timing out. For example: const load_dirs = (dirs ...

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

React Material-UI Multiple Select with Checkboxes not displaying initial selections as checked

I am fairly new to working with React and MUI, so please bear with me. Currently, I am in the process of learning how to create Multiple Select Options with checkboxes by populating the Dropdown Options from an Array. Although I have set up the initial/de ...