Record Collection Challenge I'm Stuck! [Solved]

collection[id].tracks = [value] this is where I’m lost. I don’t understand what this code mean.

Spoiler Alert!!

I got so stuck, I ended up looking at the solution.

I just wish some Pro, tell me why there is a need for this second “if” ( if(collection[id][prop]) ), nested in the first block:

function updateRecords(id, prop, value) {
  if (prop === "tracks" && value !== "") {
   if(collection[id][prop]) {
    collection[id][prop].push(value);
   }
   else {
    collection[id][prop]=[value];
   }
  } else if (value !== "") {
    collection[id][prop] = value;
  } else {
    delete collection[id][prop];
  }

  return collection;
}

Thanks for any answer.

You can’t push to an array that doesn’t exist, and if you would just do like the else statement then you would be deleting what’s already inside the array

So if the array does exist, the new value is pushed to it, if it doesn’t exist, it is created

1 Like

For logical and didactics purposes, would it not make sense to declare it first then? as:

function updateRecords(id, prop, value) {
if(collection[id][prop]) {   
  if (prop === "tracks" && value !== "") {
   collection[id][prop].push(value);
   }

best regards.

No, because if prop isn’t track you are overwriting or creating a string, which you do in the exact same - it is only for tracks which is an array that you need to be careful if it already exists or not

1 Like

I dont see any problem in this task,easy.

function updateRecords(object, id, prop, value) {

    if(object.hasOwnProperty(id)&&prop!=="tracks"){

      if(value){

        object[id][prop] = value;

      }else{

       delete object[id][prop];

      }

   }else if(object.hasOwnProperty(id)&&prop==="tracks"){

     if(value){

      if(object[id].hasOwnProperty("tracks")){

        object[id][prop].push(value);

       }else{

        object[id][prop] = [];

        object[id][prop].push(value);

      }  

    }else{

      if(object[id].hasOwnProperty("tracks")){

       delete object[id][prop];

      }

    }

   }

   return object;

 }

But if i did it on a real project I would check id

1 Like

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.