Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda