【问题标题】:Parsing nested JSON data with angular2使用 angular2 解析嵌套的 JSON 数据
【发布时间】:2019-01-28 23:05:08
【问题描述】:

我正在使用 Angular5,并且我从一个类似这样的 API 接收一些 JSON 数据

{
  Cars: {

      BMW: {
        M3: {
          description: 'BMW M3 car description'
          features: [
            {
              name: 'feature name',
              description: 'feature description'
            }
          ]
        },
        M4: {
          description: 'BMW M4 car description'
          features: [
            {
              name: 'feature name',
              description: 'feature description'
            }
          ]
        }
      },

      Audi: {
        features: [
          {
            name: 'extra feature 1',
            description: 'extra feature 1 description'
          }
        ],
        R8: {
          description: 'Audi R8 car description'
          features: [
            {
              name: 'feature name',
              description: 'feature description'
            }
          ]
        },
        R6: {
          description: 'Audi R6 car description'
          features: [...]
        }
      }
    ...
  }
}

现在,我需要在模板中以这样的结构呈现它,例如:

M3
  features...
M4
  features...
R8
  features...
R6
  features...

但问题是这些汽车模型对象(M3、M4、R8...)是作为对象内部的对象提供的(而不是我可以使用简单的 ngFor 轻松循环遍历的对象数组)。

此外,在“Audi”对象中,您会注意到与“R8”和“R6”处于同一级别的额外“功能”对象,

这需要为具有关键“额外功能”的“R8”和“R6”对象添加

(因此,如果存在与汽车模型处于同一级别的“功能”对象,则应将其移动到具有关键“额外功能”的汽车模型对象中)

所以奥迪对象最终应该是这样的:

Audi: {

  R8: {
    description: 'Audi R8 car description'
    features: [
      {
        name: 'feature name',
        description: 'feature description'
      }
    ],
    extra-features: [
      {
        name: 'extra feature 1',
        description: 'extra feature 1 description'
      }
    ]
  },
  R6: {
    description: 'Audi R6 car description'
    features: [...],
    extra-features: [
      {
        name: 'extra feature 1',
        description: 'extra feature 1 description'
      }
    ]
  }
}

最终在模板中渲染的结果是这样的:

M3
  features...
M4
  features...
R8
  features...
  extra-features...
R6
  features...
  extra-features...

【问题讨论】:

    标签: javascript json angular ngfor


    【解决方案1】:

    尝试类似:

    const cars;
    
    myCars = YourJsonData;
    myCars.forEach((car, index, self) => {
      cars.push(index);
      car.forEach((model, indexM, self) {
         cars[index].push(indexM);
         model.forEach((feat, indexF, self) {
           cars[index][indexM].push([indexF => indexF.value]);
         });
      });
    });
    

    可以优化,用JS不太好。

    在模板中类似:

    *ngFor="let car in cars"
    *ngIf="car.features"
    *ngIf="car.extra-features"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多