首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当对象深度嵌套在JavaScript中时,如何将整个对象作为输出?

当对象深度嵌套在JavaScript中时,如何将整个对象作为输出?
EN

Stack Overflow用户
提问于 2018-08-19 01:52:10
回答 2查看 60关注 0票数 1
代码语言:javascript
复制
 let common = {
        "id": 1364184,
        "url": "http:\/\/www.tvmaze.com\/episodes\/1364184\/the-big-bang- 
        theory-11x12-the-matrimonial-metric",
        "name": "The Matrimonial Metric",
        "season": 11,
                  "number": 12,
        "airdate": "2018-01-04",
        "airtime": "20:00",
        "airstamp": "2018-01-05T01:00:00+00:00",
        "runtime": 30,
        "image": {
          "medium": "sonie",
          "original": "agarwal" 
        },
        "summary": "<p>To discover who would be most qualified to be best 
         man and maid of honor at their wedding, Sheldon and Amy subject 
         their friends to a series of secret experiments. Also, Penny 
         reveals her true feelings about Amy.<\/p>",
        "_links": {
      "self": {
            "href": "http:\/\/api.tvmaze.com\/episodes\/1364184"
          }
        }
      }
 for (var x in common) {
 console.log(x+ "=" +common[x]);
if ( x === "image" ){
let z = common.image
 for (var y in z) {
  console.log( x + " = " + y+ " : " +z[y]);
 }
 }if ( x === "_links" ){
 let z = common._links.self
 for (var y in z) {
  console.log( x + " = " + y+ " : " +z[y]);
  }
 }
}

output is posted in the image

我写了获取输出的大部分代码,但我想要的是,去掉一些带有黑色框的输出,如图所示。所以请帮帮我。

EN

回答 2

Stack Overflow用户

发布于 2018-08-19 02:01:43

如果您只是想将深度嵌套的对象作为字符串获取,则可以执行以下操作:JSON.stringify(value)

举个例子:

代码语言:javascript
复制
var value = {
  one: {
    two: {
      three: [
        'one', 
        'two', 
        'three'
      ]
    }
  }
}
var asString = JSON.stringify(value);

console.log(asString)  # "{"one":{"two":{"three":["one","two","three"]}}}"
票数 1
EN

Stack Overflow用户

发布于 2018-08-19 02:08:31

之所以会发生这种情况,是因为每次都会运行以下行,而不进行检查:

代码语言:javascript
复制
console.log(x+ "=" +common[x]); 

相反,您可以使用if-else结构:

代码语言:javascript
复制
for (var x in common) {
  if (x === "image") {
    let z = common.image;
    for (var y in z) {
      console.log(x + " = " + y + " : " + z[y]);
    }
  } else if (x === "_links") {
    let z = common._links.self;
    for (var y in z) {
      console.log(x + " = " + y + " : " + z[y]);
    }
  } else {
    console.log(x + "=" + common[x]);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51911251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档