0

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);
});
1
  • Just something to keep in mind for the future, using a for ... in or for ... of loop gives you a lot less headache when it comes to scoping. Commented Feb 13, 2018 at 21:25

3 Answers 3

3

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

movie.forEach(function (element) {
    element.format = "film";
});
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.