0

I have an object that is a collection of index numbers. Under each number there are two properties and an array. I am trying to write a function that will accept arguments of the index number, the property to be updated, and the value. So far I can’t figure out how to access the array.

var myObject = 
{
"0001":
  {
  "prop1": ""
  "prop2": ""
  "prop3": []
  }

To access prop1 and prop2 I was able to just use an if statement:

if (prop == "prop1 ")
{
  collection[id].prop1 = value;
}
else if(prop == "prop2")
{
  collection[id].prop2 = value;
}

When I tried to get to the array it fell apart. I tried a few things by the most logical one seemed to be:

 if(prop == "prop3")
 {
   collection[id].prop3.push(value);
 }

Where am I going wrong here?

B Minster
  • 331
  • 3
  • 16

1 Answers1

0

Maybe you need to create an array first.

if (prop == "tracks") {
    collection[id].tracks = collection[id].tracks || [];
    collection[id].tracks.push(value);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • The array already exists. It is initialized as an empty array. – B Minster Oct 27 '16 at 14:44
  • No error, just doesn't update. It almost seems like it's not meeting the conditions of the if statement and just moving on. – B Minster Oct 27 '16 at 14:56
  • you could insert a `console.log(...)` and have a look at the console. – Nina Scholz Oct 27 '16 at 15:02
  • Trying to do that. I'm in freecodecamp's environment and so I don't have access to the console unless it throws an error. I also don't have access to the browser's console because of security at my work. I'll have to try that when I get home. – B Minster Oct 27 '16 at 15:22
  • you could use alert instead. – Nina Scholz Oct 27 '16 at 15:24
  • Thanks, I hadn't thought of that. So the conditions are being met but the code isn't doing anything inside any of the if's that deal with the array. I tried both solutions here and it didn't work for me. – B Minster Oct 27 '16 at 15:36