如何从角度6的json对象中获取值? [英] How to fetch value from json object in angular 6?

查看:107
本文介绍了如何从角度6的json对象中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,其中另一个对象内包含多个对象.我想获取数据,但不使用该值的键.我想在那里迭代键和值,并想以角度6动态地打印它们.

I have one json file which contains multiple objects inside another object. I want to fetch data but not using key of that value. I want to iterate there key and values and want to print them dynamically in angular 6.

{
  "name" : "abc",
  "tags" : "def",
  "updated-by" : "ijk",
  "property" : {
    "description" : "abcd",
    "type" : "string"
  },
  "sources" : {
    "input" : {
      "type" : "lmn",
      "properties" : {
        "key" : "opq"
      }
    }
  }
}

我们可以像迭代数组一样迭代对象吗?如果有人可以帮助您?

Can we iterate objects like we iterates array. If anyone can help?

推荐答案

我建议参考这个StackOverflow问题,

据我所知,* ngFor不仅可以用于数组,还可以用于对象.

As far as I know, *ngFor can be used not only for arrays but also for Objects.

希望以上链接会有所帮助.

Hope the above link helps.

对于其值包含对象的键,也可以检查键的对应值是否为对象.

Also for the keys whose values contain objects, you could check if the corresponding value of the key is an object.

例如,

if( (typeof A === "object") && (A !== null) )

其中A是键的对应值.如果A确实是一个对象,请再次使用* ngFor遍历该对象.

where A is the corresponding value of the key. If A is indeed an object, use *ngFor again to iterate over the object.

我尚未测试以下代码,但希望您对我要说的内容有所了解,

I haven't tested the following code but I hope you get an overview of what I am trying to say,

@Component({
  selector: 'app-myview',
  template: 
  `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}
    <div *ngIf="checkFunction(items[key])">
      <div *ngFor="let key2 of objectKeys(items[key])">            
         {{key2 + ' :' + items[key][key2]}}
      </div>
    </div>
  
  </div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
  
  checkFunction(obj){
    if( (typeof obj === "object") && (obj !== null) )
    {
      return true;
    }
    else{
      return false;
    }
  }
}

这篇关于如何从角度6的json对象中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆