【问题标题】:Handling json objects in angular 6以角度 6 处理 json 对象
【发布时间】:2019-03-01 02:06:07
【问题描述】:

我得到一个像下面这样的 json 对象

 response = [
{
  'a': [
    {
      'b': [
        {
          'c': [
            {
              'name': 'abc',
              'value': 900
            }
          ]
        }
      ]
    }
  ]
},
{
  'a': [
    {
      'b': [
        {
          'c': [
            {
              'name': 'abc',
              'amount': 900
            }
          ]
        }
      ]
    }
  ]
}
];

现在我正在使用下面的代码循环对象

this.response.forEach(
    (event) => {
      event.a.forEach(
          () => {

          }
      );
    }
)

在编译时我收到一条错误消息

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((callbackfn: (value: { 'b': { 'c': { 'name': string; 'value': number; }[]; }[]; }, index: number...' has no compatible call signatures.

上述错误的任何修复?提前致谢

【问题讨论】:

  • 是什么给了你这样的回应?
  • 可能是因为您在内部 forEach 中使用了无参数 lambda () => { ... }。使用(b) => { ... } 可能会解决问题。

标签: angular typescript


【解决方案1】:

这是访问 c.namec.amount

的方式
response.forEach(element => {
      element['a'].forEach(a => {
           a['b'].forEach(b => {
               b['c'].forEach(c => {
                     console.log(c.name);
                     console.log(c.amount);
               });
            });
      });
 });

JSFiddle => https://jsfiddle.net/jpwga2du/

【讨论】:

    【解决方案2】:
    this.response.forEach((el1: any) => {
      el1.a.forEach((el2: any) => {
        el2.b.forEach((el3: any) => {
          el3.c.forEach(el4 => {
            console.log(el4)
          });
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2020-10-24
      • 1970-01-01
      相关资源
      最近更新 更多