简体   繁体   中英

Creating an array destructing a nested object

I need to create an array of the id: 's within the entity: variable nested within the stakes variable in the object proposal . When I use this code to destructure the object:

const {
   stakes: {
      entity: { id: SupportersId },
    },
 } = proposal
  console.log(SupportersId)

I get the error: TypeError: Cannot read property 'id' of undefined

This is a `stakes' variable example nested within the proposal object that I am applying the code to:

0: 
 amount: BigNumber 
    c: [100000] 
    e: 19 
    s: 1 
    __proto__: Object 
 createdAt: 1616006864000 
 entity: {id: "0x60893...734",
        __typename: "Supporter"} 
 id: "appAddress:0x8blahblah...entity:0x608same" 
 proposal: null 
 type: "Add" 

So when I run:

const {stakes} = proposal
console.log(stakes)

I get the above object. When running:

const {stakes: {entity}, }= proposal 

I get:

4 Undefined
10 Undefined
10 Undefined
...

A number that doesnt seem to have any relevance to what it is that I am dealing with. Hopefully someone can help me with this. I feel like I need to add an index number to the variable in the way that you would when mapping through an array to create an element however, I am also not certain on what that would look like either, sadly. Ultimately I am going to pass this list as a child to another function that will map through it in another form in my app to pull image and profile data from the id to create a "personal card" if that helps. Any help or advice would be greatly appreciated, thanks!

Here's a counterexample that destructures correctly. I suspect the difference between this and your situation is that your proposal.stakes is likely an array, which I infer from the 0: in your output.

 const proposal = { stakes: { amount: 10n, c: [100000], e: 19, s: 1, createdAt: 1616006864000, entity: { id: "0x60893...734", __typename: "Supporter" }, id: "appAddress:0x8blahblah...entity:0x608same", proposal: null, type: "Add", } }; const { stakes: { entity: { id: SupportersId }, }, } = proposal; console.log(SupportersId) const {stakes: {entity}, }= proposal; console.log(entity);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM