如何从angular 6中的嵌套json对象中动态获取值?

时间:2019-02-21 08:11:05

标签: angular angular5 angular6

我想访问包含多个嵌套对象的json文件中的数据,并且想动态打印它们而无需考虑其中的数据是什么。我想在内部动态打印键值。

我的json

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

如果我的键包含对象,那么它应该进入该对象内部然后打印其值,但是如果它也是另一个对象,那么它也应进入该对象内部然后打印其键值。它应该动态循环。代码必须为4角或更高。如果有人可以提供帮助。

2 个答案:

答案 0 :(得分:1)

您正在寻找的行为已被JSON.stringify(jsonObject)方法覆盖。

您还可以控制间距和pretty print the JSON

答案 1 :(得分:0)

您可以使用递归函数。


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

function checkNested(obj) {
    for (let prop in obj) {        
        if (obj.hasOwnProperty(prop)) {
            if (typeof obj[prop] == "object"){
                console.log(`Key: ${prop}`)
                checkNested(obj[prop]);
            } else {
              console.log(`Key: ${prop} 'value: ${obj[prop]}`)
            }
        }
    }
}


checkNested(myObj)