Estoy tratando de cambiar un valor de una matriz. He estado investigando y el código no parece funcionar. tengo varios
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>
Solución del problema
Tienes que manejar dos casos:
Si .findIndex()
devuelve un número distinto de -1, actualice el elemento
.findIndex()
devuelve -1. Entonces toma acción. por ejemplo, inserte un nuevo objeto, no haga nada, devuelva un 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"})
No hay comentarios.:
Publicar un comentario