我有一个对象数组,看起来像这样:
posts = [
{
id: 1,
title: "abc",
body: "lorem ipsum",
},
{},
] 我想通过ES6解构来访问这棵树的最里面的键(id,title,body)。目前,我可以通过三个阶段来实现这一点:
const { posts } = data;
const [post] = posts;
const {title, body} = post;但我想知道是否可以在一行中做到这一点。
发布于 2019-09-25 17:06:47
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发布于 2019-09-25 17:06:23
这应该会完成第一个项目的工作:
let [{id, title, body}] = posts;For循环:
posts.map(({id, title, body}) => { /* ... */})发布于 2019-09-25 17:05:18
只需将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);
https://stackoverflow.com/questions/58094859
复制相似问题