Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create an array of objects in Javascript?

I understand that in Javascript, I can create an object like this:

var cup = {};

Furthermore, I can set properties like this:

cup.color = 'Blue';
cup.size = 'Large';
cup.type = 'Mug';

Can I create an array of cups? For example:

cup[0].color = 'Blue';
cup[1].size = 'Large';
cup[2].type = 'Mug';
like image 731
cleverpaul Avatar asked Dec 20 '16 23:12

cleverpaul


People also ask

How do you create an array of objects in JavaScript?

Creating an array of objects We can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]

How do you create an array of objects?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

Can you have an array of objects in JavaScript?

Iterating through an array is possible using For loop, For..in, For..of, and ForEach(). Iterating through an array of objects is possible using For..in, For..of, and ForEach().

What is the correct way to create a JavaScript array with 3 items?

An array can be created using array literal or Array constructor syntax. Array literal syntax: var stringArray = ["one", "two", "three"]; Array constructor syntax: var numericArray = new Array(3); A single array can store values of different data types.


1 Answers

Creating an array is as simple as this:

var cups = [];

You can create a populated array like this:

var cups = [
    {
        color:'Blue'
    },
    {
        color:'Green'
    }
];

You can add more items to the array like this:

cups.push({
    color:"Red"
});

MDN array documentation

like image 89
Will P. Avatar answered Oct 10 '22 07:10

Will P.