Unable to modify an element within an array using findIndex

Struggling with updating a value within an array, my research has not yielded a working solution. I have encountered multiple issues.

Array = [{
val1: "1",  
val2: "2",
nameval: "name",
val4: "3"
},{
val1: "4",
val2: "5",
nameval: "name",
val4: "6"}]


function updateName(e) {
    let pos = Array.findIndex(i => i.val1 === e.id ); 
    if (Array[pos]) {
            Array[pos][nameval] = "work";
        } else {
            Array[pos] = {
                nameval: "work",
            };
        }
        console.log(Array)
        console.log("this should be 1 but it is: " + Array.findIndex(i => i.val1 === e.id))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input onchange="updateName(this)" class="first-class" id ="4" >
</label>

Identified a potential issue in this code snippet Array.findIndex(i => i.val1. It returns -1 indicating a failure.

Referencing helpful links: https://www.geeksforgeeks.org/indexof-method-in-an-object-array-in-javascript/

Resolved an error using the suggestions provided here:

Answer №1

To effectively manage the situation, there are two scenarios to consider:

  1. When the object is located

If the .findIndex() method returns a value other than -1, it signifies that the element needs to be updated.

  1. When the object is not found

Upon receiving a return value of -1 from .findIndex(), appropriate measures need to be taken. For example, adding a new object, taking no action, or providing an error message.

const dataArray = [{
    val1: "1",  //these are actually lots of random numbers but im not gonna go though all that code 
    val2: "2",
    nameval: "name",
    val4: "3"
  },{
    val1: "4",
    val2: "5",
    nameval: "name",
    val4: "6"
  }
]


function updateName(search) {
    let pos = dataArray.findIndex(i => i.val1 === search.id ); 
    if (pos > -1) {
        // found, so update
        dataArray[pos].nameval = search.new_value;
    } else {
        // not found, take action
        // option 1)
        //   add a new entry with default data:
        dataArray.push({
            val1: search.id,
            val2: "2",
            nameval: search.new_value,
            val4: "4"
        });
        // // option 2)
        // //   add a new entry with the data passed in search
        // dataArray.push({
        //     val1: search.id,
        //     val2: search.val2,
        //     nameval: search.new_value,
        //     val4: "4"
        // });
        
        // option 3)
        // take no action
    }
    console.log(dataArray)
    console.log("id: "+search.id+" now index is " + dataArray.findIndex(i => i.val1 === search.id))
}

updateName({id:"1", new_value: "work"})
updateName({id:"4", new_value: "developer"})
updateName({id:"878", new_value: "freelancer"})

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

Using React and Typescript, implement an Ant Design Table that includes a Dropdown column. This column should pass

Next Row: { title: "Adventure", render: (item: ToDoItem) => { //<- this item return ( <Dropdown overlay={menu}> <Button> Explore <DownOutlined /> </Button> </Dropdown&g ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

What is the most effective way to send multiple values through the <option> value attribute?

Currently, I am in the process of creating an online shopping item page. To display all the necessary information about an item (such as price, image, name, etc.), I use the 'item_id' to loop through a database containing item info. Additionall ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

The webpage fails to return to its original position after the script has been executed

My website has a sticky div that stays at the top when scrolling down, but does not return to its original position when scrolling back up. Check out this example function fixDiv() { var $div = $("#navwrap"); if ($(window).scrollTop() > $div.data("top ...

Axios successfully fulfills a promise despite the request being canceled while using React.StrictMode

In my React project, I'm using axios with React.StrictMode enabled by default, causing components to render twice. To handle this behavior, I've set up an abort control for my axios instance and call its abort() method in the useEffect clean-up f ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

What is the best way to display the next and restart buttons at the bottom of every question?

How can I display the next and restart buttons at the bottom of each question in my JavaScript quiz web app? Why is the user unable to choose the wrong answer from the provided options? I'm facing difficulty showing the next and restart buttons for i ...

JavaScript button not responding to click event

Here is the initial structure that I have: <section id="content"> <div class="container participant"> <div class="row"> <div class="input-group"> <div class="input-group-prepend"> ...

Is there a way to dynamically update one input field while another input field is being modified? [HTML / JS]

I have a form with 3 input fields. One of the inputs is disabled, while the other two are enabled. The goal is to combine the values entered in the enabled fields to populate the disabled field. How can this be achieved? Is it possible for the value in th ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Vue-router and middleman combination displaying '404 Error' upon page refresh

I'm in the process of developing a website that utilizes Middleman (Ruby) on the backend and VueJS on the front end, with vue-router managing routing. Specifically, in my vue-router configuration, I am rendering the Video component on /chapter/:id as ...

What methods can be used to determine if a webm file contains audio or video content?

In the process of creating an uploader using ReactJS, I encounter an issue related to identifying whether uploaded files are video or audio. Specifically, when users upload audio files with a .webm extension (e.g., music.webm) and the MIME type is set as & ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

JQuery appended Bootstrap Modal to Body, but it refuses to close

After going through the process of appending the modal to the body and getting the text box working, I encountered an issue when trying to close it on the AJAX success event - none of my attempted solutions seem to be effective. var id; var refundAmount ...

NodeJS and Express server is having trouble accessing the linked JavaScript file(s) from the HTML document

I'm facing a challenge with my web hosting server on AWS while using express.js. I have encountered the following error: root@ip(censored):/home/ubuntu/(censored)# /home/ubuntu/(censored)/routes/index.js:15 $(document).ready(function() { ^ Referen ...

step-by-step guide for resolving issues with downloading files in node.js

I've been attempting to download files from my server using node.js with the res.download function from Express, but I keep getting an undefined error. The folder path is D:\program\web\java_script\Node\my_project\ketabk& ...

What are some effective strategies for enhancing the performance of React user interfaces?

I'm currently dealing with a performance challenge in one of my React applications. What are some best practices to enhance the responsiveness of the User Interface? One approach could be to minimize the usage of conditional expressions like { carIsR ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically. Unfortunately, I have run into an issue where the delete function does not work when the button is pressed. Her ...