简体   繁体   English

创建一个数组来破坏嵌套的 object

[英]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 .我需要在entity:中创建一个id:的数组,该变量嵌套在 object proposal中的stakes变量中。 When I use this code to destructure the object:当我使用此代码解构 object 时:

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

I get the error: TypeError: Cannot read property 'id' of undefined我收到错误: 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:这是一个嵌套在提案 object 中的“赌注”变量示例,我将代码应用于:

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.我得到了上面的 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.最终,我将把这个列表作为一个孩子传递给另一个 function,它将 map 在我的应用程序中以另一种形式通过它,从 id 中提取图像和配置文件数据以创建“个人卡”,如果有帮助的话。 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.我怀疑这与您的情况之间的区别在于您的proposal.stakes可能是一个数组,我从0:在您的 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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