将 Json 转换为数组并在 html 中使用 for 循环在 angular 中迭代时出错

Error while converting Json to an array and iterating in html using for loop in angular

我正在使用 angular,我正在从 api get call 获取数据,如下列之一。 如前所述,我将此 json 转换为数组。当我在 html 上重复此操作时,出现错误。 我的目标是使用 ngfor 迭代 html 中的以下列数据。 请帮助我实现功能。

[{"Parent": null, "GradeCode": null, "BrandName": "CORONA", "Manufacturer": null, "Description": null, "BrandStatus": 1, "ManufacturerName": "", "ParentBrandName": "CORONA", "id": 7101}, 
{"Parent": "hhh", "GradeCode": null, "BrandName": "TSINGTAO", "Manufacturer": null, "Description": null, "BrandStatus": 1, "ManufacturerName": "", "ParentBrandName": "TSINGTAO", "id": 7100}]

我将这个数据推送到一个数组

data: any = [];

我将上面的“数据”从 json 转换为数组,如下所示。 但是,我得到的错误是:

" 错误类型错误:this.data.forEach 不是函数。

data1=[];
  ngOnInit()
  {
    var StringifyData=JSON.stringify(this.data)
    console.log(this.data)
    this.data.forEach((item,index)=>{
        var obj;
        obj={
          Parent:item.Parent,
          text:item.BrandName,
        }
       this.data1.push(obj)
    });
     console.log(JSON.stringify(this.data1))
  }
}



您不应该将数组推送到 data 对象。

您可以将数组中的元素分配或推送到 data 对象。

所以,您可以这样做:

this.data = [
      {
        Parent: null,
        GradeCode: null,
        BrandName: "CORONA",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "CORONA",
        id: 7101
      },
      {
        Parent: "hhh",
        GradeCode: null,
        BrandName: "TSINGTAO",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "TSINGTAO",
        id: 7100
      }
    ];

或者这样:

[
      {
        Parent: null,
        GradeCode: null,
        BrandName: "CORONA",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "CORONA",
        id: 7101
      },
      {
        Parent: "hhh",
        GradeCode: null,
        BrandName: "TSINGTAO",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "TSINGTAO",
        id: 7100
      }
    ];

    [
      {
        Parent: null,
        GradeCode: null,
        BrandName: "CORONA",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "CORONA",
        id: 7101
      },
      {
        Parent: "hhh",
        GradeCode: null,
        BrandName: "TSINGTAO",
        Manufacturer: null,
        Description: null,
        BrandStatus: 1,
        ManufacturerName: "",
        ParentBrandName: "TSINGTAO",
        id: 7100
      }
    ].forEach(f => this.data.push(f));

注:这里第一个比较好尝试

工作演示StackBlitz

试试这个:

Array.prototype.forEach.call(this.data, item => {
//logic goes here... 
})