0

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.

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

After destructuring , i have get a first value alone , how can get all the values of food and push into new array
thank you for the valuable answer i have learned destructuing from you..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.