Home > Enterprise >  trying to grab a value from an array in javascript
trying to grab a value from an array in javascript

Time:01-29

im trying to make it so it only shows specific sizes for the array i have, this is the array

const products = [{
    name: "14K bracelet",
    id: "1",
    description: "Beautfull 14K gold Bracelet",
    price: 100,
    size: [1, 2, 3, 4]
    
}

and this is how im trying to grab the values from it

                    <Dropdown.Item className="dropdown-item" href="#/action-1">{products.size[0]}</Dropdown.Item>

but im getting this error

TypeError: Cannot read properties of undefined (reading '0')

CodePudding user response:

Do it like this: const products = { name: "14K bracelet", id: "1", description: "Beautfull 14K gold Bracelet", price: 100, size: [1, 2, 3, 4]
}

CodePudding user response:

you are trying to get access to to an object in array so it should be like

let product = [{name:'test', size:[1,2,3,4]}]

console.log(product[0].size[1])

CodePudding user response:

You should use 'products' as an array instead of object.

Arrays have elements(object - keys). For working with them you must use indexes(f.e. array[0] for getting the first element).

For more information:

Arrays: https://www.w3schools.com/js/js_arrays.asp

Objects: https://www.w3schools.com/js/js_objects.asp

const products = [{
    name: "14K bracelet",
    id: "1",
    description: "Beautfull 14K gold Bracelet",
    price: 100,
    size: [1, 2, 3, 4]
    
}];

console.log(products[0].size[0]);

  •  Tags:  
  • Related