Let's say we have the object below:
const page = {
name: 'Page 1',
page_category: [
{
postId: 1,
catId: 1,
category: {
id: 1,
name: 'category 1'
}
},
{
postId: 3,
catId: 2,
category: {
id: 2,
name: 'category 2'
}
},
]
}
To get the first object in the page_category array, in a destructuring manner, We would do this:
const { page_category: [first] } = page
But what would it be if we wanted to get the first object's category field?
You can destructure the object within the array destructuring:
const { page_category: [{category}] } = page;
const page = {
name: 'Page 1',
page_category: [{
postId: 1,
catId: 1,
category: {
id: 1,
name: 'category 1'
}
},
{
postId: 3,
catId: 2,
category: {
id: 2,
name: 'category 2'
}
},
]
};
const { page_category: [{category}] } = page;
console.log(category);
The destructuring assignment syntax is analogous to the syntax of creating the object literal, the below formatting shows how they have the same shape. You can use this idea to assist with your destructuring patterns:
const {
page_category: [
{
category
}
]
} = page;
To destructure the first object's category field.
const {page_category: [ {category} ]} = page;
console.log("category ==>", category);
This way you will find the first category object.