Nod*_*ros 0 javascript arrays destructuring ecmascript-6
假设我们有以下对象:
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'
}
},
]
}
Run Code Online (Sandbox Code Playgroud)
要以解构方式获取 page_category 数组中的第一个对象,我们将这样做:
const { page_category: [first] } = page
Run Code Online (Sandbox Code Playgroud)
但是如果我们想获取第一个对象的类别字段会怎样呢?
您可以在数组解构中解构对象:
const { page_category: [{category}] } = page;
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
解构赋值语法类似于创建对象文字的语法,下面的格式显示了它们如何具有相同的形状。您可以使用这个想法来帮助您的解构模式:
const {
page_category: [
{
category
}
]
} = page;
Run Code Online (Sandbox Code Playgroud)