I am trying to build an array with a custom string index to get the item faster. The console.log of arr2 is showing the 3 items wierdly but I can’t enum them, it is only showing the first item
I m using react so I can’t build an object instead
let arr = [
{
"barcode": "27034FAZ019",
"name": "Item 1",
"price": 0.99,
"stock": 10
},
{
"barcode": "404E47HV1768",
"name": "Item 2",
"price": 2.99,
"stock": 10
},
{
"barcode": "325KS6130LG76",
"name": "Item 3",
"price": 5.99,
"stock": 10
}
]
let arr2 = []
arr.forEach((item) => {
arr2[item.barcode] = item
})
console.log(arr2); //shows 3 items wierdly
arr2.forEach((item) => {
console.log(item); //shows only the first item
})
The question is how to enum all the items in arr2 because the forEach only output the first
>Solution :
You are trying to set the key of objects within an array, instead of creating an object with keys,
i.e instead of
let arr2 = []
arr.forEach((item) => {
arr2[item.barcode] = item
})
you would want:
let obj2 = {}
arr.forEach((item) => {
obj2[item.barcode] = item
})