How to Use Spread Operator for Array Destructuring from a Nested Object in JavaScript?

Estimated read time 1 min read

In JavaScript, you can use the spread operator ... to destructure an array from a nested object. Here’s an example:

let obj = {
  data: [1, 2, 3, 4, 5]
};

let [...array] = obj.data;
console.log(array); // Output: [1, 2, 3, 4, 5]

In this example, the spread operator is used to destructure the data array from the obj object and store it in a new array array. The spread operator takes all elements of an array and spreads them into individual elements, so in this case, array would contain [1, 2, 3, 4, 5].

You can also use the spread operator to destructure nested arrays from nested objects:

let nestedObj = {
  data: {
    array: [1, 2, 3, 4, 5]
  }
};

let {
  data: { array: [...nestedArray] }
} = nestedObj;
console.log(nestedArray); // Output: [1, 2, 3, 4, 5]

In this example, the spread operator is used to destructure the array property from the nested data object of the nestedObj object and store it in a new array nestedArray. The spread operator takes all elements of the array property and spreads them into individual elements, so in this case, nestedArray would contain [1, 2, 3, 4, 5].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply