What is the best way to implement a dynamic input in a findIndex callback function using Javascript?

Referenced from :

let myArray = [
  {id: 0, name: "Jhon"},
  {id: 1, name: "Sara"},
  {id: 2, name: "Domnic"},
  {id: 3, name: "Bravo"}
],
    
//Identify the index of a specific object using findIndex method.    
objIndex = myArray.findIndex((obj => obj.id == 1));

//Display object in Console.
console.log("Before update: ", myArray[objIndex])

//Modify object's name property.
myArray[objIndex].name = "Laila"

//Display updated object in console.
console.log("After update: ", myArray[objIndex])

//Identify index of specific object utilizing findIndex method.    
    objIndex = myArray.findIndex((obj => obj.id == 1));

In the snippet above, I'm using obj.id == 1.

I intend to make it dynamic and not rigid. Is there a way to accomplish this?

Answer №1

Instead of using the number 1 directly in the findIndex callback, you can utilize a variable.

function changeObject() {
  let myArray = [
    {id: 0, name: "Jhon"},
    {id: 1, name: "Sara"},
    {id: 2, name: "Domnic"},
    {id: 3, name: "Bravo"}
  ]
  
  let id = document.getElementById('myInput').value
  

  //Find index of specific object using findIndex method.    
  objIndex = myArray.findIndex((obj => obj.id == id));

  //Log object to Console.
  console.log("Before edit: ", myArray[objIndex])

  //Modify object's name property.
  myArray[objIndex].name = "Laila"

  //Log object to console again.
  console.log("After edit: ", myArray[objIndex])
  
 }
<label>Modify object</label>
<input type="text" id="myInput" value="1">
<input type="button" value="Modify" onClick="changeObject()">

Answer №2

let employeesArray = [
  {id: 0, name: "John"},
  {id: 1, name: "Sara"},
  {id: 2, name: "Dominic"},
  {id: 3, name: "Bravo"}
]

const id = prompt('Please enter the ID of the employee:')
    
//Use findIndex method to locate the index of a specific object.    
objIndex = employeesArray.findIndex((obj => obj.id == id));

//Display the object before updating.
console.log("Before updating: ", employeesArray[objIndex])

//Update the employee's name property.
employeesArray[objIndex].name = "Laila"

//Display the updated object on the console.
console.log("After updating: ", employeesArray[objIndex])

I utilized the prompt function in this example to create a user input scenario for entering employee IDs. Run the code snippet to view the outcome.

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

Library in JS for accessing or duplicating a repository on GitHub

How can I connect my Node.js server to a GitHub repository? I need the server to be able to retrieve the source files from the git repository, either by cloning the repo into a temporary folder or accessing them directly. ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

What are the steps for encoding a value using jquery serialize?

I attempted to encode all values using the following code: encodeURIComponent($("#customer_details").serialize()); Unfortunately, it did not produce the desired results. Is there a method to retrieve all elements on a form and individually encode each v ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...

Tips for effectively running multiple XMLHttpRequests in a loop

While running XMLHttpRequest inside .map(), everything operates smoothly. list.map(function(file) { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () {} xhr.onerror = function () {} xhr.upload.addEventListener(& ...

"Is there a way to adjust the range slider to display currency instead of

I stumbled upon this amazing slider on codepen. Can someone guide me on how to adjust it to display a range from €500 to €6000 while keeping the vibrant red background? I've attempted various solutions like: <input id = "range" type = "range ...

How to dynamically reference an input textbox ID using javascript or jquery

I have a button titled: GridView1__ctl2_AddButton0 While I can extract the middle part "ctl2" (and variations for each row), I am trying to use it to populate a textbox among many with similar names. GridView1__ctl2_txtStormTimeOn Currently, I could ac ...

NodeJS isn't executing the GET method as expected

In my project, I am utilizing two separate files named main.js and task.js. The main.js file is responsible for sending API calls to all the methods that are defined in the task.js file. This is what the main.js file looks like: const express = require(&a ...

Tips for generating a numeric whole number input field with Vuetify

After researching the topic on Vuetify's specific number input component, I am attempting to create a numeric input field. The value for both input and output is currently unknown, meaning it could be either undefined or null in order to allow cleari ...

Converting an object to an array with the help of jQuery

I have been working with a json file and created an object using jquery's $.get method. Here is what it looks like when I log it: console.log(array); [Object, Object, Object, Object, Object, Object, Object, Object] 0 : Object country ...

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

Command is not displaying JavaScript

Having difficulty grasping the task at hand. As a Mac user, my goal is to construct a 3D portfolio but I'm facing challenges. The issue lies in JavaScript not appearing on Variants. Upon entering "npm init vite.js/app," a framework is generated, follo ...

Having issues with a local image not loading in React?

I am trying to display a local image in React js. After referring to this solution, I have tried the following code - <img src={require('../public/images/icon.png').default} /> The image "icon.png" is stored in my public folder, and I&apos ...

Guide on testing conditional rendering in components with Jest and Enzyme

Within my React component, I have a conditional rendering block that looks like this: {(props.email.primary.isPending) ? <PendingComponent emailAddress={props.email.primary.pendingEmail} /> : <SecondaryEmailContact ...

What is the most effective method for displaying or concealing a form row when a specific drop-down option is chosen?

I am working on a form dropdown list where I want to enable users to select "Other." When the user selects the "Other" option, I would like a form row to appear below so they can type in their own text. Below is the code I have written for this functionali ...

Unable to retrieve JSON element using Fetch

I'm attempting to retrieve a JSON file and exhibit its components within a div. Here is the JSON data I have: [ { "0":{ "host_id":"129230780", "host_names":"STK Homes", ...

Avoiding the unnecessary re-rendering of input fields in React when their values change

I am developing a form that is dynamically generated using JSON data fetched from an API. The JSON structure includes information about the input elements to be rendered, such as name, type, placeholder, validation rules, and more. { name: { elemen ...

Tips for incorporating your personal touch while utilizing Snipcart

I have created an ecommerce platform with GatsbyJS and Snipcart, but I am struggling to override the default theme provided by Snipcart. When I try to change the main default CSS through gatsby-config.js, it does not seem to work. Does anyone have a soluti ...

What is the most effective way to update the React state based on an if-else condition within a

I am facing an issue where I have a component in my project that needs to update the parent state when clicked, but there is an if-else condition causing the state not to update in the parent component. In my project, I have two boxes with an if-else cond ...

Tips for effectively integrating data from MongoDB into a React application

Currently, I am utilizing two components to extract data from the database. One component is used to loop through the data entries, while the second one is dedicated to accessing and displaying the details for each entry. Within my database, there is a fie ...