Reputation: 167
This is my array:
const [arr, setArr] = React.useState([
{
"id": 1,
"barcode": "8851907264888",
"qty" : 1
},
{
"id": 2,
"barcode": "8857124022072",
"qty": 1
}
]);
this is my function:
const hasBarcode = (arr, barcode) => arr.some(el => el.barcode === barcode);
const handleUpdate=()=>{
let x = 8851907264888;
for(let i = 0;i < arr.length;i++){
if(hasBarcode(arr[i], x) == true){
let newArr = [...arr];
newArr[i].qty = newArr[i].qty + 1;
setArr(newArr);
}
}
}
My problem is in the for loop
, I would like to check each of array index, if each index contains the same barcode
as x
, i would like to make addtion for qty + 1
for that specific index. But here it shown error as Cannot read property 'some' of undefined
Upvotes: 0
Views: 57
Reputation: 10498
The error in your code is here
if(hasBarcode(arr[i], x) == true){
because you are trying to apply a method whose first argument is an array, to an object.
The correct one should be if(hasBarcode(arr, x) == true){
You could do the following, though, using filter
and forEach
functions of Array
:
const handleUpdate = () => {
let x = 8851907264888;
let newArr = [...arr];
newArr.filter(el => el.barcode === barcode).forEach(el => el.qty++);
setArr(newArr);
}
Upvotes: 2
Reputation: 700
the error in your code you passing an object to hasBarcode() not array also you can do it like this
const handleUpdate = () => {
let x = 8851907264888;
let newArr = arr.map((obj) => {
if (obj.barcode && obj.barcode == x) {
obj.qty = obj.qty + 1;
}
return obj;
});
setArr(newArr);
};
Upvotes: 3
Reputation: 1828
const hasBarcode = (arr, barcode) => arr.some(el => el.barcode === barcode);
const handleUpdate=()=>{
let x = 8851907264888;
for(let i = 0;i < arr.length;i++){
if(hasBarcode(arr, x) == true){
let newArr = [...arr];
newArr[i].qty = newArr[i].qty + 1;
setArr(newArr);
}
}
}
Upvotes: 2