I'm having a problem reaching an array element using a variable as the array index. If I use a number as the array index it works, but the variable does not. The variable has shown to be a number tho.
///the array to access:
const listaProd = [
{
name: 'Água..........',
price: 2.5,
},
{
name: 'Coca-cola.......',
price: 6,
},
{
name: 'Almoço executivo..',
price: 25.5,
},
/////etc....
];
///////////////etc....
/// these are indexes of listaProd to be listed
const ar = [1, 2];
{
///ar is set as the array: [1, 2] here.
/// this means I wanna get listaProd[1] and listaProd[2]
ar.map((p, c) => {
console.log('-', p);
{
/**p is a number, either 1 or 2, checked */
}
let index = parseInt(p);
{
/**to be sure it is a number... */
}
return (
<div className="pedido_client" key={c}>
{/**-----it does work! --------*/}
{listaProd[1].name}
{/**does not work */}
{listaProd[p].name}
{/**does not work */}
{listaProd[index].name}
{/**does not work */}
{listaProd.at(index).name}
</div>
);
})
}
I'm getting the error:
Error in /~/src/App.js (144:1) listaProd[p] is undefined
So, zero is working in the first case as an index, but either 'p' or 'index' are not working as an index. Why?
the whole thing is here for now: (please able the blocked cookies to work) https://stackblitz.com/edit/react-xek249?file=src/App.js,src/style.css
you can fork it and test it.
CodePudding user response:
You are mapping this array const ar = [1, 2];
ar.map((value,index)=>console.log(value)) // it will return 1 , 2
And in your array you have index 1 but index 2 is undefined.
{ ar.map((p, c) => {
let index = parseInt(p);
return (
<div className="pedido_client" key={c}>
{listaProd[index% ar.length].name }
</div>
);
})
}
{listaProd[index% ar.length].name }
allow you to stay within the range of array indexes.
Suggestion
- your ar array is kind of meaningless here, you can directly map this array
listaProd
. - Or you can use index directly from map method.
ar.map((val,index)=><div>{arr[index].name})
CodePudding user response:
Sedat Polat answered in a comment, so I cannot flag it as the answer,
But it was an extra comma matter.
Thank You!