针对特定数组元素与分配解构

问题描述 投票:0回答:1

我使用了一些分配解构在我的MongoDB /后端节点,以处理一些后期处理。我只是想了解这种解构如何运作的,如果在多个元素和嵌套数组的数组的情况下,如果我可以输入我要定位的元素。

就拿这样的代码:

    services: [
      ,
      {
        history: [...preSaveData]
      }
    ]
  } = preSaveDocObj;

我的假设是,在上面的代码‘服务’的“”将默认为寻找数组中的第一个元素。正确?

现在,如果我有一个文件结构,看起来像这样(见下文),我知道我想要的目标“服务”元素,其中“服务”等于“typeTwo”,我该怎么做?:

 {
   _id: 4d39fe8b23dac43194a7f571,
   name: {
     first: "Jane",
     last: "Smith"
   }
   services: [
    {
     service: "typeOne",
     history: [ 
       { _id: 121, 
         completed: true,
         title: "rookie"
       },
       { _id: 122, 
         completed: false,
         title: "novice"
       } 
      ]
     },
     {
      service: "typeTwo",
      history: [ 
       { _id: 135, 
         completed: true,
         title: "rookie"
       },
       { _id: 136, 
         completed: false,
         title: "novice"
       } 
      ]
     }
   ]
 }

如何修改这些代码(见下文),专门针对“服务”组,其中“服务”等于“typeTwo”?

    services: [
      ,
      {
        history: [...preSaveData]
      }
    ]
  } = preSaveDocObj;
javascript ecmascript-6 destructuring
1个回答
1
投票

不要overdestructure,只是find

 const { history: [...preSavedData] } = doc.services.find(it => it.serice === "typeTwo");
© www.soinside.com 2019 - 2024. All rights reserved.