'Destructuring first object of array in JavaScript [duplicate]
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
