volume one
volume one

Reputation: 7563

How to include a loop within object creation?

I am trying to create an object to use in various places of HTML. It goes a little something like this:

MovieInfo = {
            title: Movie.value[0].title,
            meta: [
              {
                name: "description",
                content: Movie.value[0].description,
              },
              {
                name: "date",
                content: Movie.value[0].releasedate
              },
              // Try to add objects from another array
             Movie.value[1].forEach(function (Cast, index) {
             return {
                key: Cast.actorname, property: "article:tag", content: Cast.actorname
              }
          })
            ]
}

The above does not work. However if I push to the meta array after creating the MovieInfo object then it does work, like so:

MovieInfo = {
                title: Movie.value[0].title,
                meta: [
                  {
                    name: "description",
                    content: Movie.value[0].description,
                  },
                  {
                    name: "date",
                    content: Movie.value[0].releasedate
                  },
                 
                ]
    }

              // Try to add objects from another array
                 Movie.value[1].forEach(function (Cast, index) {
                 MovieInfo.meta.push({
                    key: Cast.actorname, property: "article:tag", content: Cast.actorname
                  })
              })

I have to do quite a few of these loops in different areas so I would prefer them to be done while creating MovieInfo than outside of it. Is that possible? That is, is it possible to make my first attempt work by having a loop inside the object creation itself?

Upvotes: 1

Views: 51

Answers (1)

Bergi
Bergi

Reputation: 664548

You can use an IIFE to do arbitrary things in an object literal (or really, any expression):

const MovieInfo = {
  title: Movie.value[0].title,
  meta: (() => {
    const meta = [
      {
        name: "description",
        content: Movie.value[0].description,
      },
      {
        name: "date",
        content: Movie.value[0].releasedate
      },
    ];
    for (const cast of Movie.value[1]) {
      meta.push({
        key: cast.actorname,
        property: "article:tag",
        content: cast.actorname
      });
    }
    return meta;
  })(),
};

In this case, I would however recommend to simply build the array using concat and map:

const MovieInfo = {
  title: Movie.value[0].title,
  meta: [
    {
      name: "description",
      content: Movie.value[0].description,
    },
    {
      name: "date",
      content: Movie.value[0].releasedate
    },
  ].concat(Movie.value[1].map(cast => ({
    key: cast.actorname,
    property: "article:tag",
    content: cast.actorname
  }))),
};

Upvotes: 2

Related Questions