Javascript: optimal method for creating an array of objects

What is the best way to efficiently populate an array with numerous objects created using a constructor?

I have a constructor function that creates TV and movie objects:

function Media(name, boxCover) {
    this.name = name;
    this.boxCover = boxCover;
};

I am creating many objects that I want to store in an array. My initial approach did not work as expected:

var table = [
var avengers = new Media("avengers",'../assets/boxcovers/avengers.jpg');
var blade_runner = new Media("blade_runner",'../assets/boxcovers/blade_runner.jpg');
var brave = new Media("brave",'../assets/boxcovers/brave.jpg');
var catching_fire = new Media("catching_fire",'../assets/boxcovers/catching_fire.jpg');
var django = new Media("django",'../assets/boxcovers/django.jpg');
var finding_nemo = new Media("finding_nemo",'../assets/boxcovers/finding_nemo.jpg');
];

I also attempted to use table.push( at the beginning of each line. Do I really need to list each object individually in the array like this, or is there a more efficient method to avoid duplication?

table = [avengers, blade_runner, etc.

Answer №1

To define this structure in code, follow these guidelines:

var collection = {
    key1: value1,
    key2: value2
};

If you prefer your variable to be an object with accessible properties like collection.property, initialize it as shown below:

var collection = {
    item1: new Item("item1",'../assets/images/item1.jpg'),
    item2: new Item("item2",'../assets/images/item2.jpg'),
    item3: new Item("item3",'../assets/images/item3.jpg')
    //... and so forth
};

For the ability to loop through them, consider creating an array instead:

var collection = [
    new Item("item1",'../assets/images/item1.jpg'),
    new Item("item2",'../assets/images/item2.jpg'),
    new Item("item3",'../assets/images/item3.jpg')
    //... and so forth
];

Answer №2

Your code is currently utilizing incorrect syntax. Consider using the following revised version:

function Multimedia(title, coverImage) {
    this.title = title;
    this.coverImage = coverImage;
};

var gallery = [
 new Multimedia('avengers','../assets/coverImages/avengers.jpg'),
 new Multimedia('blade_runner','../assets/coverImages/blade_runner.jpg')         
];

Answer №3

A more concise way to achieve the same result is by using the following syntax:

let mediaArray = [];
let item = {
    title: {},
    coverImage: {}
};
mediaArray.push({
    title: "inception",
    coverImage: '../assets/covers/inception.jpg'
});
mediaArray.push({
    title: "interstellar",
    coverImage: '../assets/covers/interstellar.jpg'
});
alert(mediaArray.length);

Alternatively, you can populate the array using an object:

item.title = "matrix";
item.coverImage = '../assets/covers/matrix.jpg';
mediaArray.push(item);
alert(mediaArray.length + ":" + mediaArray[1].title);

Answer №4

class Movie {
    constructor(title, cover) {
        this.title = title;
        this.cover = cover;
    }
}

class MovieCatalog {
    constructor(data) {
        const catalog = {};
        data.forEach(item => {
            catalog[item[0]] = new Movie(item[0], item[1]);
        });
        return catalog;
    }
}

const movieData = [
    ["avengers", '../assets/boxcovers/avengers.jpg'],
    ["blade_runner", '../assets/boxcovers/blade_runner.jpg'],
    ["brave" , '../assets/boxcovers/brave.jpg'],
    ["catching_fire", '../assets/boxcovers/catching_fire.jpg'],
    ["django", '../assets/boxcovers/django.jpg'],
    ["finding_nemo", '../assets/boxcovers/finding_nemo.jpg']
];

const movieCatalog = new MovieCatalog(movieData);

Answer №5

To update your variable table, just follow this structure:

var table = [
  new Media("spiderman",'../assets/boxcovers/spiderman.jpg'),
  new Media("harry_potter",'../assets/boxcovers/harry_potter.jpg'),
  new Media("shrek",'../assets/boxcovers/shrek.jpg'),
  new Media("moana",'../assets/boxcovers/moana.jpg'),
  new Media("the_lion_king",'../assets/boxcovers/the_lion_king.jpg'),
  new Media("frozen",'../assets/boxcovers/frozen.jpg')
];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

The function findOne from Mongoose seems to be non-existent, all while utilizing the Passport library

Whenever I try to implement my local strategy using the passport lib, I keep encountering this error. TypeError: UserModel.findOne is not a function I've spent hours searching for a solution that addresses this issue but haven't been successful ...

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

Create a Boxplot chart using Chart.js that dynamically adjusts the minimum and maximum values to allow for additional space on either

I am utilizing chartjs v2.9 for creating a boxplot and my code structure is as follows: function generateRandomValues(count, minimum, maximum) { const difference = maximum - minimum; return Array.from({length: count}).map(() => Math.random() * ...

There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function: <script> $.ajax({ url: "http://192.168.0.101/commerce/pro ...

Is there a way to adjust the size of an iframe that includes an external source while also shifting the contents?

How can I achieve the following tasks: Delay loading of an external iFrame Adjust the dimensions of an externally sourced iFrame (e.g., 100px x 40px) Position an externally sourced iFrame off-center (e.g., 25px x 50px) Here's a code snippet example ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

Modify the state of an individual item within an array

I have a list of items that I need to show a loader for and hide it once a certain action is completed. For instance, below is my array of items: [ { "id": "69f8f183-b057-4db5-8c87-3020168307c5", "loading": null } ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data: { "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name ...

Guide on fetching data from a different php file using jQuery's .load() method?

I am trying to use a basic .load() function from jQuery to load a div element with an id from another file in the same directory when changing the selected option in a selector. However, I am having trouble getting it to work. Nothing happens when I change ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

activating a jQuery function and sending a parameter

Looking for some help with JavaScript - I'm having trouble getting this code to work. I need to trigger a predefined function from one script within my AJAX script. Specifically, I want to activate the qtip functionality on the content of a div that i ...

Switch from using `widthWidth` to `useWidth` in MUI v5 ReactJS

Currently, I am in the process of updating a project that utilizes MUI as the UI Library for my React application. I have started migrating to version 5 today, and one issue I've encountered is related to all functional components wrapped by withWidth ...

Expansive menu that stretches the full height of the webpage

I'm having difficulty making my side spry menu extend the full length of the webpage. I tried using this code: $("nav").css({ "height" : $("nav").height() }); but it still isn't working as expected. I just want the grey color, like ...

What is the reason that removing items from a list in Ruby does not function properly when used within a for loop?

let list = ['x', 'y', 'z'] for i in list list.removeFromIndex(list.indexOf(i)) end print list.displayed After running the above code, the output shows that list is now equal to ["y"]. Why didn't it remove all element ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

Is this example a strong demonstration of implementing simple inheritance in JavaScript?

Having transitioned from using Dojo, there's one specific thing that I deeply miss - Dojo's declare() function. Developing a rather complex application, I found myself extensively modifying Node's lang.inherits() to enhance its functionality ...

405 - Sorry, this method is not allowed for deletion

The issue at hand involves a Spring RESTful web service and a client. When attempting a DELETE request on the server, the following error is encountered: -> DELETE http://localhost:8080/employee/3/logout 405 (Method Not Allowed) Despite implementing th ...