Search code examples
javascriptdestructuring

Destructuring values from array nested inside an object.


Given the following object:

const object = {
    greeting: "hi",
    farewell:"bye",
    specialArray:[10,20,30,40,50]
} 

I need to retrieve the 3 first elements of the array into 3 separate variables a , b , c

how?


Solution

  • Just assign to an array with the variables for a destructuring assignment.

    const object = {
            greeting: "hi",
            farewell: "bye",
            specialArray: [10, 20, 30, 40, 50]
        },
        [a, b, c] = object.specialArray;
    
    console.log(a, b, c);