解构对象内部数组中的对象

时间:2019-09-25 09:03:26

标签: javascript ecmascript-6 destructuring

我有一个看起来像这样的对象数组:

posts = [
  {
    id: 1,
    title: "abc",
    body: "lorem ipsum",
  },
  {},
] 

我想通过ES6解构访问此树的最内层键(idtitlebody)。目前,能够通过三个阶段实现这一目标:

const { posts } = data;
const [post] = posts;
const {title, body} = post;

但是我想知道是否可以在一行中做到这一点。

3 个答案:

答案 0 :(得分:1)

只需将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);

答案 1 :(得分:1)

这应该完成第一项的工作:

let [{id, title, body}] = posts;

对于循环:

posts.map(({id, title, body}) => { /* ... */})

答案 2 :(得分:1)

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