【问题标题】:Destructuring objects inside an array inside an object在对象内部的数组中解构对象
【发布时间】:2019-09-25 09:03:26
【问题描述】:

我有一个如下所示的对象数组:

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

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

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

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

【问题讨论】:

    标签: javascript ecmascript-6 destructuring


    【解决方案1】:

    这应该为第一项工作:

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

    for 循环:

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

    【讨论】:

    • 有没有办法在不使用地图的情况下获得所有ids?
    • 嗯,你需要某种形式的循环来遍历对象。我认为const ids = posts.map(({id}) => id) 形式是最简单、最易读的形式,但您也可以选择for-loop。所以不,没有循环或数组函数(Array.mapArray.forEachÀrray.reduce 等)就无法做到这一点。
    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

      只要把posts[0]放在右边:

      posts = [
        {
          id: 1,
          title: "abc",
          body: "lorem ipsum",
        },
        {},
      ];
      const { title, body } = posts[0];
      
      console.log(title, body);

      您也可以将[]s 放在左侧,在{} 周围,但它不那么可读:

      posts = [
        {
          id: 1,
          title: "abc",
          body: "lorem ipsum",
        },
        {},
      ];
      const [{ title, body }] = posts;
      
      console.log(title, body);

      【讨论】:

        猜你喜欢
        • 2017-08-13
        • 2015-10-05
        • 2023-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-30
        • 1970-01-01
        相关资源
        最近更新 更多