0

I am using some assignment destructuring in my MongoDB/Node backend in order to handle some post-processing. I'm just trying to understand how this destructuring works, and if, in the case of an array of multiple elements and nested arrays, if I can input the element I want to target.

Take for instance this code:

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

My assumption is that the "," in "services" for the above code will default to looking at the first element in the array. Correct?

Now, if I have a document structure that looks like this (see below), and I know I want to target the "services" element where "service" is equal to "typeTwo", how would I do that?:

 {
   _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"
       } 
      ]
     }
   ]
 }

How can I edit this code (see below) to specifically target the "services" array where "service" is equal to "typeTwo"?

    services: [
      ,
      {
        history: [...preSaveData]
      }
    ]
  } = preSaveDocObj;
Muirik
  • 6,049
  • 7
  • 58
  • 116
  • 2
    The comma means that nothing is done to `services[0]` and that `services[1]` is assigned to the `{history: [...preSaveData]}` expression. – Bergi Feb 11 '19 at 15:34
  • Why not just use `filter()` on services array? I'm not sure if you can use destructuring to match for specific values. – Shidersz Feb 11 '19 at 15:36
  • btw, why the rest syntax? – Nina Scholz Feb 11 '19 at 15:45
  • @NinaScholz _"So, taking for example my two objects below, is there a way I can just pull out the the last element in the "history" array for obj2"_ https://stackoverflow.com/q/54555427/ – guest271314 Feb 11 '19 at 15:48
  • 2
    @guest271314, it wuld be sufficient to rename the target, like `history: preSaveData` – Nina Scholz Feb 11 '19 at 15:54

1 Answers1

1

Don't overdestructure, just find:

 const { history: [...preSavedData] } = doc.services.find(it => it.serice === "typeTwo");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151