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

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

问题描述

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

<代码>{"name" : "abc",标签":定义",更新者":ijk",财产" : {"描述": "abcd",类型":字符串"},来源":{输入" : {类型":lmn",特性" : {键":opq"}}}}

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

解决方案

我建议参考这个 StackOverflow 问题,

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

希望以上链接有帮助.

同样对于值包含对象的键,您可以检查该键对应的值是否为对象.

例如

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

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

我还没有测试下面的代码,但我希望你能大致了解我想说的内容,

@Component({选择器:'app-myview',模板:`<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]}}

`})导出类 MyComponent {objectKeys = Object.keys;items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };构造函数(){}检查功能(对象){if( (typeof obj === "object") && (obj !== null) ){返回真;}别的{返回假;}}}

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?

解决方案

I would suggest referring this StackOverflow question,

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.

For instance,

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

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天全站免登陆