0

My object is getting turned into an array

this.projects = {};
var outerThis = this;
for(var i=0; i<10; i++){
 console.log(this.projects); // at this point projects is Object {}
 if(!(i in Object.keys(this.projects))){
 this.projects[i] = {title:"", trackOneUrl:"", trackTwoUrl:""};
 console.log(this.projects); // now its [object object]
 return;
 }
}

when I do:

this.projects[i] = {title:"", trackOneUrl:"", trackTwoUrl:""}

projects goes from being an Object to an Array.

What I was trying to achieve is

{'1':{title:"", trackOneUrl:"", trackTwoUrl:""}}

instead I get

[{title:"", trackOneUrl:"", trackTwoUrl:""}]
Ian Stapleton Cordasco
29.2k4 gold badges74 silver badges73 bronze badges
asked Mar 15, 2016 at 20:40
14
  • Look at your code, you're treating your object like an array so you're going to get array like behavior Commented Mar 15, 2016 at 20:44
  • Running this code in node yields { '0': { title: '', trackOneUrl: '', trackTwoUrl: '' } } which looks correct based on your desired outcome. Commented Mar 15, 2016 at 20:51
  • 1
    Did you try using this.projects.i = /// your assignment. jsfiddle.net/fNPvf/25810 Commented Mar 15, 2016 at 20:52
  • @Aj1 That seems like the way to go, I suggest you make that into an answer and explain why the way he's currently trying to do it is mutating his object into an array! Commented Mar 15, 2016 at 20:55
  • 1
    [object Object] is not an array. Commented Mar 15, 2016 at 20:57

3 Answers 3

1

Your this.projects will remain an object and it does exactly what you wanted it to be.

That [object Object] doesn't mean your projects becomes an array, that's a string representation of an object. Try calling String({}) and you will see the same effect.

answered Mar 15, 2016 at 20:56
Sign up to request clarification or add additional context in comments.

Comments

0

this.projects is what is known as an object literal. {}

Create and array literal using []

From there you can assign an object to each index in the array using a simple for loop.

answered Mar 15, 2016 at 20:46

1 Comment

this doesn't answer the question. The user is trying to create an object and use obj[] to access the properties on the object.
0

What you have will work fine if you take out the return.

answered Mar 15, 2016 at 20:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.