Bradg89
Bradg89

Reputation: 153

Adding new property to existing javascript object

I am trying to add format: "film" to each object in the array but I can't figure it out.

var movie = [
    {title: "A Clockwork Orange", year: "1971", raiting: "8.3", genre: "Crime, Drama, Sci-Fi"},
    {title: "Full Metal Jacket", year: "1987", raiting: "8.3", genre: " Drama, War"},
    {title: "Pulp Fiction", year: "1994", raiting: "8.9", genre: "Crime, Drama"},
    {title: "Fight Club", year: "1999", raiting: "8.8", genre: "Drama"},
    {title: "Interstellar", year: "2014", raiting: "8.6", genre: "Adventure, Drama, Sci-Fi"}
];


movie.forEach(function () {
    movie.format = "film";
});


movie.forEach(function (element) {
    console.log(element);
});

Upvotes: 0

Views: 153

Answers (3)

Tim Han
Tim Han

Reputation: 166

If you are into ES6 too, you can certainly do this with the fat arrow.

movie.forEach(element => element.format = "film");

Upvotes: 0

Ele
Ele

Reputation: 33726

Using goes to operator.

var movie = [    {title: "A Clockwork Orange", year: "1971", raiting: "8.3", genre: "Crime, Drama, Sci-Fi"},    {title: "Full Metal Jacket", year: "1987", raiting: "8.3", genre: " Drama, War"},    {title: "Pulp Fiction", year: "1994", raiting: "8.9", genre: "Crime, Drama"},    {title: "Fight Club", year: "1999", raiting: "8.8", genre: "Drama"},    {title: "Interstellar", year: "2014", raiting: "8.6", genre: "Adventure, Drama, Sci-Fi"}];

let i = movie.length;
while (i --> 0) movie[i].format = 'film';
console.log(movie);
.as-console-wrapper {
  max-height: 100% !important
}

Upvotes: 1

Evya
Evya

Reputation: 2375

You need to pass an argument to function and add the new property to it

movie.forEach(function (element) {
    element.format = "film";
});

Upvotes: 3

Related Questions