【问题标题】:TypeError: Cannot set property 'name' of undefinedTypeError:无法设置未定义的属性“名称”
【发布时间】:2021-08-03 15:58:40
【问题描述】:

我正在尝试将 JSON 响应的一些值映射到另一个变量,但出现错误“无法设置未定义的属性名称”

export interface Data
{
   description: any;
   name : any;
}

在主类内部定义了以下数据

actionData : any;
action:Data[]=[];

getData()
  {
      this.spref.getNewData().subscribe(
        response => {
          this.actionData = response;
          for(let i=0;i<this.actionData.length;i++)
          {
             
               this.action[i].name = this.actionData[i].name;
               this.action[i].description = this.actionData[i].description;
          }
    
          })
         
        },
        error => {
          console.log('Failure: ', error);
        }
      );

   }

这种格式的actionData的响应

[{
description: "pqrs"
jsonType: "com.iti.dexcenter.common.object.NewData"
name: "abc"
value: "xyz"
}]

我希望动作数据以这种格式存储

[{
description: "pqrs"
name: "abc"
}]

提前致谢!

【问题讨论】:

    标签: json angular typescript mapping angular11


    【解决方案1】:

    action[i] 如果未初始化,则未定义。因此,在为其设置任何属性之前,您需要对其进行初始化,如下所示:

    actionData : any;
    action:Data[]=[];
    
    getData()
      {
          this.spref.getNewData().subscribe(
            response => {
              this.actionData = response;
              for(let i=0;i<this.actionData.length;i++)
              {
                   this.action[i] = {
                       name: this.actionData[i].name;
                       description: this.actionData[i].description;
                   }
              }
        
              })
             
            },
            error => {
              console.log('Failure: ', error);
            }
          );
    
       }
    

    【讨论】:

    • 添加这些行时出错“类型 {} 缺少以下属性‘数据’:描述”
    • 这取决于您使用的Data 类型的定义。它不在您提交的代码中,所以我看不到它。我会修改我的答案
    • 将动作类型从 Data[] 更改为任何适合我的工作。但我想知道为什么它不能正常使用 Data[] 类型
    • actionData 对象的数组,因此action 数组中的所有对象都必须有descriptionname
    • 是的,你会这样做:` interface Data { optionalField?: string; } `
    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 2015-10-16
    • 2015-09-09
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多