使用循环访问JSON中的对象属性

时间:2018-02-01 02:12:30

标签: javascript json loops

我正在尝试了解有关循环的更多信息,并尝试以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等对象属性?

3 个答案:

答案 0 :(得分:2)

您不能在对象上使用 .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]);
}

答案 1 :(得分:0)

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

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);
    }
}

答案 2 :(得分:0)

我迟到了。
这将做你想要的。

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 );
}