在对象内的数组内解构对象
Destructuring objects inside an array inside an object
我有一个对象数组,如下所示:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
]
我想通过 ES6 解构访问这棵树的最里面的键(id
、title
、body
)。目前,我可以分三个阶段实现:
const { posts } = data;
const [post] = posts;
const {title, body} = post;
但我想知道是否可以在一行中这样做。
就把posts[0]
放在右边:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const { title, body } = posts[0];
console.log(title, body);
您也可以将 []
放在左侧,{}
周围,但这样可读性不佳:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const [{ title, body }] = posts;
console.log(title, body);
这应该完成第一项的工作:
let [{id, title, body}] = posts;
For 循环:
posts.map(({id, title, body}) => { /* ... */})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const [{ id, title, body: newBody }] = posts
我有一个对象数组,如下所示:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
]
我想通过 ES6 解构访问这棵树的最里面的键(id
、title
、body
)。目前,我可以分三个阶段实现:
const { posts } = data;
const [post] = posts;
const {title, body} = post;
但我想知道是否可以在一行中这样做。
就把posts[0]
放在右边:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const { title, body } = posts[0];
console.log(title, body);
您也可以将 []
放在左侧,{}
周围,但这样可读性不佳:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const [{ title, body }] = posts;
console.log(title, body);
这应该完成第一项的工作:
let [{id, title, body}] = posts;
For 循环:
posts.map(({id, title, body}) => { /* ... */})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
];
const [{ id, title, body: newBody }] = posts