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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.