Mohamed Sahir
Mohamed Sahir

Reputation: 2543

Destructuring of an array of objects getting undefined

I have tried to destructure the Array object, getting undefined.

 var menus = [{
   food: "pizza",
   drink: "coke"
 }, {
   food: "burger",
   drink: "pepsi"
 }, {
   food: "sandwitch",
   drink: "coke"
 }, {
   food: "popcorn",
   drink: "coke"
 }];

 var {
   food: team,
   drink: sports
 } = menus;

 console.log({
   team
 });

Output: team is undefined.

It seems like a syntax issue.

Upvotes: 0

Views: 307

Answers (1)

Ori Drori
Ori Drori

Reputation: 191946

You need to destructure an object inside the array.

You can use array destructuring with object destructuring (the 1st item in this case):

const menus = [{"food":"pizza","drink":"coke"},{"food":"burger","drink":"pepsi"},{"food":"sandwitch","drink":"coke"},{"food":"popcorn","drink":"coke"}];
 
const [{ food:team,drink:sports }] = menus;
 
console.log({team});

Or destructure a specific object in the array:

const menus = [{"food":"pizza","drink":"coke"},{"food":"burger","drink":"pepsi"},{"food":"sandwitch","drink":"coke"},{"food":"popcorn","drink":"coke"}];
 
const { food:team,drink:sports } = menus[2];
 
console.log({team});

To get all values to a new array use Array.map():

const menus = [{"food":"pizza","drink":"coke"},{"food":"burger","drink":"pepsi"},{"food":"sandwitch","drink":"coke"},{"food":"popcorn","drink":"coke"}];
 
const teams = menus.map(({ food: team }) => ({ team }));
 
console.log(teams);

Upvotes: 1

Related Questions