1

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?

1
  • When I tried to get to the array it fell apart. what error did you got on the console? Commented Oct 27, 2016 at 14:03

1 Answer 1

0

Maybe you need to create an array first.

if (prop == "tracks") {
    collection[id].tracks = collection[id].tracks || [];
    collection[id].tracks.push(value);
}
Sign up to request clarification or add additional context in comments.

6 Comments

The array already exists. It is initialized as an empty array.
No error, just doesn't update. It almost seems like it's not meeting the conditions of the if statement and just moving on.
you could insert a console.log(...) and have a look at the console.
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.
you could use alert instead.
|

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.