cfoster5
cfoster5

Reputation: 1826

Get object properties for objects in array

Using plain Javascript, I am trying to access a property, theatricalrelease for all objects in an array, movies.

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"
  }
}];

for (var i = 0; i < movies.length; i++) {
  console.log(movies[i]);
  //TRIED
    for (var property in movies[i]) {
      if (movies[i].hasOwnProperty(property)) {
          console.log(property);
      }
    }
  }
}

As you can see, I tried to use another for loop inside another one as I expected it to loop over the object's index names. Instead, logging property gave me the name of each index. How can I access each movie's theatrical realease?

Upvotes: 0

Views: 54

Answers (2)

Ele
Ele

Reputation: 33736

According to your approach: Only one element:

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

movies.forEach(({theatricalrelease}) => console.log(theatricalrelease));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Tyler
Tyler

Reputation: 1039

The problem is you have an array of one object and an extra } bracket at the bottom of the code. I made some changes to your array to what I believe you intended. This now prints the theatrical release in your console.log.

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

for (var i = 0; i < movies.length; i++) {
  console.log(movies[i]);
  console.log('theatrical release', movies[i]['theatricalrelease'])
}

Upvotes: 2

Related Questions