skip to Main Content

Hey Fellow stackoverflowers, recently i got a new problem accessing array inside array and that inside array containg two objects product and quantity. Now i want to access that inside array how can i do that. Please if you have any solution please share with me:

const arrayOfArrays = [
 [
   { product: { name: 'Product 1', price: 10 }, quantity: 1 },
   { product: { name: 'Product 2', price: 20 }, quantity: 2 }
 ]
];

3

Answers


  1. you need first to take 0th element of outer array, then you can enumerate internal array, like this:

    const arrayOfArrays = [
     [
       { product: { name: 'Product 1', price: 10 }, quantity: 1 },
       { product: { name: 'Product 2', price: 20 }, quantity: 2 }
     ]
    ];
    
    console.log(arrayOfArrays[0][0].product.name);
    console.log(arrayOfArrays[0][1].product.name);
    Login or Signup to reply.
  2. const innerArray = arrayOfArrays[0];

    // Accessing the first element of the inner array
    const firstElement = innerArray[0];

    // Accessing the product name of the first element
    const productName = firstElement.product.name;

    console.log(productName);

    Login or Signup to reply.
  3. Use double square brackets to access the inner array and the desired attribute within each object to access the Product and Quantity objects within the nested array.

     const arrayOfArrays = [
      [
        { product: { name: 'Product 1', price: 10 }, quantity: 1 },
        { product: { name: 'Product 2', price: 20 }, quantity: 2 }
      ]
    ];
    
    // Access the 'product' object from the first item in the array
    const firstProduct = arrayOfArrays[0][0].product;
    console.log(firstProduct.name); // Product 1
    console.log(firstProduct.price); // 10
    
    // Access the 'quantity' property from the second item in the array
    const secondQuantity = arrayOfArrays[0][1].quantity;
    console.log(secondQuantity); // 2

    Like this, you can access properties from the nested array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search