【问题标题】:Accessing object properties in JSON with a loop使用循环访问 JSON 中的对象属性
【发布时间】:2018-02-01 02:12:30
【问题描述】:

我正在尝试了解有关循环的更多信息并尝试访问 JSON 格式的对象属性。

我的 JS 是:

var movies = {
  "Black Panther" : {
    "title" : "Black Panther",
    "theatricalrelease" : "2/16/2018"
  },
  "Infinity War" : {
    "title" : "Avengers: Infinity War",
    "theatricalrelease" : "5/4/2018"
  },
  "Captain Marvel" : {
    "title" : "Captain Marvel",
    "theatricalrelease" : "TBA"
  }
}

console.log(movies); //logs correctly
console.log(movies.length); //logs undefined

for (var i = 0; i < movies.length; i++) {
  console.log(movies[i]); // doesn't log anything
}

如何访问 titletheatricalrelease 等对象属性?

【问题讨论】:

标签: javascript json loops


【解决方案1】:

您不能在对象上使用 .length,因为它适用于数组。

但是你可以使用 Object.Keys.Lengh

var movies = {
  "Black Panther" : {
    "title" : "Black Panther",
    "theatricalrelease" : "2/16/2018"
  },
  "Infinity War" : {
    "title" : "Avengers: Infinity War",
    "theatricalrelease" : "5/4/2018"
  },
  "Captain Marvel" : {
    "title" : "Captain Marvel",
    "theatricalrelease" : "TBA"
  }
}

 
console.log(Object.keys(movies).length);
for(var key in movies) {
   console.log(movies[key]);
}

【讨论】:

    【解决方案2】:

    您可以通过这种方式访问​​标题并获取长度:

    var movies = {
      "Black Panther" : {
        "title" : "Black Panther",
        "theatricalrelease" : "2/16/2018"
      },
      "Infinity War" : {
        "title" : "Avengers: Infinity War",
        "theatricalrelease" : "5/4/2018"
      },
      "Captain Marvel" : {
        "title" : "Captain Marvel",
        "theatricalrelease" : "TBA"
      }
    }
    var totalMovies = Object.keys(movies).length;
    console.log(totalMovies);
    
    for (var key in movies) {
        if (movies.hasOwnProperty(key)) {
            console.log( movies[key].title);
            console.log( movies[key].theatricalrelease);
        }
    }
    

    【讨论】:

      【解决方案3】:

      我来晚了。
      这会做你想做的。

      var movies = {
        "Black Panther" : {
          "title" : "Black Panther",
          "theatricalrelease" : "2/16/2018"
        },
        "Infinity War" : {
          "title" : "Avengers: Infinity War",
          "theatricalrelease" : "5/4/2018"
        },
        "Captain Marvel" : {
          "title" : "Captain Marvel",
          "theatricalrelease" : "TBA"
        }
      }
      
      var moviesArray = Object.keys(movies);
      
      for (var i = 0; i < moviesArray.length; i++) {
        var index = moviesArray[i];
        console.log( "Title: " +  movies[index].title );
        console.log( "Theatrical Release: " +  movies[index].theatricalrelease );
      }

      【讨论】:

        猜你喜欢
        • 2015-10-07
        • 1970-01-01
        • 2020-01-31
        • 2016-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 2011-12-04
        相关资源
        最近更新 更多