Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
not able to change array item with findIndex

I am trying to change a value from an array. I have been researching and the code doesn't seem to work. I have multiple

Array = [{
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(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>

I know of at least one problem which is at the beginning of this code Array.findIndex(i => i.val1. That returns -1 which means that it failed.

Here are some of the links I use: https://www.geeksforgeeks.org/indexof-method-in-an-object-array-in-javascript/

I was also getting an error and this code supposedly fixed it: https://bobbyhadz.com/blog/javascript-cannot-set-property-of-undefined

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have to handle two cases:

  1. object is found

If .findIndex() returns a number other than -1, then update the element

  1. object is not found

.findIndex() returns -1. Then take action. e.g. insert a new object, do nothing, return error

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"})

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda