Member-only story

Destructuring an Object Inside an Array with a Single Statement — A Common Interview Question

Vinodh Thangavel
2 min readJul 11, 2023

--

When working with arrays of objects in JavaScript, you might be asked in an interview how to extract a specific value from an object in the array using a single destructuring statement. Let’s see how to fetch the name of the second student from the following array:

Example Array

javascript
Copy code
const students = [
{ name: 'Vinodh', dept: 'ECE' },
{ name: 'Vasanth', dept: 'ECE' },
{ name: 'Bharathi', dept: 'ECE' },
{ name: 'Yuganath', dept: 'ECE' },
{ name: 'Prasanth', dept: 'ECE' },
];

Solutions (Best Comes First)

  1. Using Array Destructuring Directly:
  2. The most concise and efficient way to extract the name of the second student is by using array destructuring:
  • javascript
  • Copy code
  • const [,{name}] = students; console.log(name); // Outputs: Vasanth
  1. In this solution, the array destructuring [,{name}] skips the first element and destructures the name property from the second element in the array.
  2. Using slice Method with Destructuring:
  3. Another approach is to slice the array to get the second element and then destructure it:
  • javascript
  • Copy code

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet