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
You have to handle two cases:
If .findIndex() returns a number other than -1, then update the element
.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"})