0

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"?

3
  • object with index? Commented Jun 12, 2017 at 16:24
  • Do you mean one Array? Commented Jun 12, 2017 at 16:26
  • Updated the question @WashingtonGuedes Commented Jun 12, 2017 at 16:30

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

That will replace the value in the index "0" with another value in each loop. I want to push it or add it so at the end in the position "0" I will have multiple arrays.
Updated my answer
I was missing the conditional validation :) now it's working, thanks Alexey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.