How to initialize empty array of objects?
javascript - How to create an empty array of a given size? - Stack Overflow
arrays - Create an empty object in JavaScript with {} or new Object()? - Stack Overflow
javascript - Declaring array of objects - Stack Overflow
Hello,
var arr: [{ name: string }] = [ ] // error
var arr: [{ name: string }] = [ { } ] // works, however, array length is 1 and not 0
How can I initialize it without adding an element inside it? Thank you.
1) To create new array which, you cannot iterate over, you can use array constructor:
Array(100) or new Array(100)
2) You can create new array, which can be iterated over like below:
a) All JavaScript versions
- Array.apply:
Array.apply(null, Array(100))
b) From ES6 JavaScript version
- Destructuring operator:
[...Array(100)] - Array.prototype.fill
Array(100).fill(undefined) - Array.from
Array.from({ length: 100 })
You can map over these arrays like below.
Array(4).fill(null).map((u, i) => i)[0, 1, 2, 3][...Array(4)].map((u, i) => i)[0, 1, 2, 3]Array.apply(null, Array(4)).map((u, i) => i)[0, 1, 2, 3]Array.from({ length: 4 }).map((u, i) => i)[0, 1, 2, 3]
var arr = new Array(5);
console.log(arr.length) // 5
Objects
There is no benefit to using new Object(), whereas {} can make your code more compact, and more readable.
For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:
var myObject = {
title: 'Frog',
url: '/img/picture.jpg',
width: 300,
height: 200
};
Arrays
For arrays, there's similarly almost no benefit to ever using new Array() over [] — with one minor exception:
var emptyArray = new Array(100);
creates a 100 item long array with all slots containing undefined, which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').
My recommendation
- Never use
new Object();— it's clunkier than{}and looks silly. - Always use
[]— except when you need to quickly create an "empty" array with a predefined length.
Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.
var objectA = {} //This is an object literal
var objectB = new Object() //This is the object constructor
In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.
For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..
Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.
I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Depending on what you mean by declaring, you can try using object literals in an array literal:
var sample = [{}, {}, {} /*, ... */];
EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:
function getDefaultObjectAt(array, index)
{
return array[index] = array[index] || {};
}
Then use it like this:
var sample = [];
var obj = getDefaultObjectAt(sample, 0); // {} returned and stored at index 0.
Or even:
getDefaultObjectAt(sample, 1).prop = "val"; // { prop: "val" } stored at index 1.
Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:
getDefaultObjectAt(sample, 2) = { prop: "val" };
Just do:
if(obj.race!==undefined && obj.race.length===0){
obj.race = [""];
}
Or:
if(obj.race!==undefined && obj.race.length===0){
obj.race.push("");
}
EDIT:
For all elements
for(var key in obj){
if(obj[key]!==undefined && obj[key].length===0){
obj[key] = [""];
}
}
I'm not sure why you've marked it up in that way. If you're passing key–value pairs to PHP, then it should look as follows:
var obj = {
age: "23",
part: "0",
race: {
"Value 1",
"Value 2"
},
state: "AL",
gender: "1",
county: "9999",
consent: "9999"
};
That way, each value would be passed to PHP (as it's a string, despite being empty).