Member-only story
Destructuring an Object Inside an Array with a Single Statement — A Common Interview Question
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)
- Using Array Destructuring Directly:
- 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
- In this solution, the array destructuring
[,{name}]
skips the first element and destructures thename
property from the second element in the array. - Using
slice
Method with Destructuring: - Another approach is to slice the array to get the second element and then destructure it:
- javascript
- Copy code