Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build an array with string index

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading