DJ22T
DJ22T

Reputation: 1640

Add an object to an array in a specific index

How can I add an object to a new empty array, in a specific index.

Let's say "0"

I have a forEach loop and I build an object with it

var array = [];

 var myObject = {
    value1: value1,
    value2: value2
 };

I can generate as many "myObject" as the times the forEach loops

How can I add all those "myObject" into "array" on the index "0"?

Upvotes: 0

Views: 166

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17721

Square brackets to the rescue:

var obj = {}
for (var i = 0; i < 5; i++) {
   if (!obj["val"+i]) {
     obj["val"+i] = []
   }
   obj["val"+i].push("val"+i)
}

Upvotes: 2

Related Questions