To create an array of persons:
var persons = []; // initialize the array
persons.push({firstName:"John", lastName:"Doe", age:46}); // Add an object
persons.push({firstName:"Joanne", lastName:"Doe", age:43}); // Add another object
To retrieve the value at a specific index:
persons[1].firstName // "Joanne"
persons[1].lastName // "Doe"
persons[1].age // 43
To iterate through the array use a for loop, or any kind of loop:
for (var i = 0; i < persons.length; i++) {
console.log( persons[i].firstName ); // writes first names to console
}
Answer from johndoe33 on Stack OverflowHow can i list an array of objects in Javascript? - Stack Overflow
What is the best way to create an array of objects in Javascript? - Stack Overflow
Array inside a JavaScript Object? - Stack Overflow
creating list of objects in Javascript - Stack Overflow
Videos
To create an array of persons:
var persons = []; // initialize the array
persons.push({firstName:"John", lastName:"Doe", age:46}); // Add an object
persons.push({firstName:"Joanne", lastName:"Doe", age:43}); // Add another object
To retrieve the value at a specific index:
persons[1].firstName // "Joanne"
persons[1].lastName // "Doe"
persons[1].age // 43
To iterate through the array use a for loop, or any kind of loop:
for (var i = 0; i < persons.length; i++) {
console.log( persons[i].firstName ); // writes first names to console
}
To create an array literal use [] instead of {}.
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
The array should be like this...
var cup = [];
After we putting properties to the array, it will be like this
[
{
"color": "blue",
"size": "large",
"type": "mug"
}
]
And you can put properties like this..
var cup = [];
cup.push({
color : 'blue',
size : 'large',
type : 'mug'
})
console.log(cup);
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output
Here is a shorter way of achieving it:
let result = objArray.map(a => a.foo);
OR
let result = objArray.map(({ foo }) => foo)
You can also check Array.prototype.map().
Yes, but it relies on an ES5 feature of JavaScript. This means it will not work in IE8 or older.
var result = objArray.map(function(a) {return a.foo;});
On ES6 compatible JS interpreters you can use an arrow function for brevity:
var result = objArray.map(a => a.foo);
Array.prototype.map documentation