Object array declaration

I have a variable that is an array, and I want each element of the array to act as a default object. To achieve this, I can do something similar in my code.

var sample = new Array(); sample[0] = new Object(); sample[1] = new Object(); 

This works fine, but I don't want to mention the index number. I want all the elements of my array to be an object. How to declare or initialize it?

 var sample = new Array(); sample[] = new Object(); 

I tried the above code, but it does not work. How to initialize an array of objects without using an index number?

+75
javascript object arrays declare
Apr 01 '13 at
source share
15 answers

Use array.push() to add an element to the end of the array.

 var sample = new Array(); sample.push(new Object()); 

To do this, use the 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 replace new Array() with [] and new Object() with {} so that it becomes the following:

 var n = 100; var sample = []; for (var i = 0; i < n; i++) sample.push({}); 
+82
Apr 01 '13 at
source share

Depending on what you mean by declaration, you can try object literals in an array literal:

 var sample = [{}, {}, {} /*, ... */]; 

EDIT: If your target is an array whose undefined elements 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 as follows:

 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" }; 
+31
Apr 01 '13 at
source share

Seeing how you answered in the comments. It seems like it would be better to use push as others suggested. This way you do not need to know the indexes, but you can add to the array.

 var arr = []; function funcInJsFile() { // Do Stuff var obj = {x: 54, y: 10}; arr.push(obj); } 

In this case, every time you use this function, it will insert a new object into the array.

+11
Apr 01 '13 at 11:50
source share

You do not need to create an empty Object ever. There is nothing you can do about them. Add work objects to the sample if necessary. Use push , as Daniel Imms suggested, and use literals, as suggested by Frederick Hamidi. It seems you want to program Javascript as C.

 var samples = []; /* If you have no data to put in yet. */ /* Later, probably in a callback method with computed data */ /* replacing the constants. */ samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */ /* or */ samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */ 

I believe that using new Array(10) creates an array with 10 undefined elements.

+10
Apr 01 '13 at
source share

You can create an array of an object type in one line (just replace the new object () with your object):

 var elements = 1000; var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); }); 
+7
May 30 '15 at 10:55
source share

You can use fill () .

 let arr = new Array(5).fill('lol'); // or if you want different objects let arr2 = new Array(5).fill().map(x => ({ test: 'a' })); 

Will create an array of 5 elements. Then you can use forEach, for example.

 arr.forEach(str => console.log(str)); 
+7
Dec 29 '16 at 20:55
source share

Well, should array.length do the trick or not? something like, I mean, you don’t need to know the range of indices if you just read it.

 var arrayContainingObjects = []; for (var i = 0; i < arrayContainingYourItems.length; i++){ arrayContainingObjects.push {(property: arrayContainingYourItems[i])}; } 

Perhaps I did not understand your question correctly, but you should be able to get the length of your array in this way and convert them to objects. Daniel gave the same answer, to be honest. You could just store the length of the array in your variable, and that will be done.

IF this should not happen, in my opinion, you cannot get the length of your array. As you said without getting the index number, you can do it like this:

 var arrayContainingObjects = []; for (;;){ try{ arrayContainingObjects.push {(property: arrayContainingYourItems[i])}; } } catch(err){ break; } 

This is not a good version above, but the loop will run until you “start” from the range of indices.

+5
Mar 18 '14 at 2:36
source share

Try it -

 var arr = []; arr.push({}); 
+3
Apr 01 '13 at 11:23
source share
 //making array of book object var books = []; var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10}; books.push(new_book); new_book = {id: "book2", name: "The_call", category: "Movies", price: 17}; books.push(new_book); console.log(books[0].id); console.log(books[0].name); console.log(books[0].category); console.log(books[0].price); // also we have array of albums var albums = [] var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15}; albums.push(new_album); new_album = {id: "album2", name: "El-leila", category: "Music", price: 29}; albums.push(new_album); //Now, content [0] contains all books & content[1] contains all albums var content = []; content.push(books); content.push(albums); var my_books = content[0]; var my_albums = content[1]; console.log(my_books[0].name); console.log(my_books[1].name); console.log(my_albums[0].name); console.log(my_albums[1].name); 

This example works with me. Snapshot to display on the browser console

+3
Jun 06 '17 at 14:30
source share

Use array.push () to add an element to the end of the array.

 var sample = new Array(); sample.push(new Object()); 

you can use it

 var x = 100; var sample = []; for(let i=0; i<x ;i++){ sample.push({}) OR sample.push(new Object()) } 
0
Dec 21 '17 at 4:59 on
source share

Using forEach, we can store data in case we already have data that we want to use to enter the business.

 var sample = new Array(); var x = 10; var sample = [1,2,3,4,5,6,7,8,9]; var data = []; sample.forEach(function(item){ data.push(item); }) document.write(data); 

Example using a simple for loop

 var data = []; for(var i = 0 ; i < 10 ; i++){ data.push(i); } document.write(data); 
0
Jan 23 '18 at 5:33
source share

If you want all the elements inside the array to be objects, you can use the JavaScript proxy to apply validation to the objects before inserting them into the array. It’s pretty simple

 const arr = new Proxy(new Array(), { set(target, key, value) { if ((value !== null && typeof value === 'object') || key === 'length') { return Reflect.set(...arguments); } else { throw new Error('Only objects are allowed'); } } }); 

Now, if you try to do something like this:

 arr[0] = 'Hello World'; // Error 

This will throw an error. However, if you insert an object, this will be allowed:

 arr[0] = {}; // Allowed 

For more information about the proxy, please follow this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

If you are looking for a polyfill implementation, you can use this link: https://github.com/GoogleChrome/proxy-polyfill

0
Feb 11 '19 at 13:57
source share

The code below from my project may be useful to you

  reCalculateDetailSummary(updateMode: boolean) { var summaryList: any = []; var list: any; if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList } else { list = this.state.chargeDefinitionList; } list.forEach((item: any) => { if (summaryList == null || summaryList.length == 0) { var obj = { chargeClassification: item.classfication, totalChargeAmount: item.chargeAmount }; summaryList.push(obj); } else { if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) { summaryList.find((x: any) => x.chargeClassification == item.classfication) .totalChargeAmount += item.chargeAmount; } } }); if (summaryList != null && summaryList.length != 0) { summaryList.push({ chargeClassification: 'Total', totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount }) } this.setState({ detailSummaryList: summaryList }); } 
0
Aug 08 '19 at 9:16
source share
 const sample = []; list.forEach(element => { const item = {} as { name: string, description: string }; item.name= element.name; item.description= element.description; result.push(item); }); return sample; 

Someone will try this .. and offer something.

0
Sep 30 '19 at 11:16
source share
 var ArrayofObjects = [{}]; //An empty array of objects. 
-7
Dec 08 '16 at 7:20
source share



All Articles