Record Collection Explanation!

Hi all,

I am working on the Record collection lesson and it does not make any sense to me.
https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-javascript/record-collection
I’ve looked up the answer and explanation, but I do not understand the code at all. Can someone please help me understand what is going on?

Thank you!

Hi,
I had the same problem with the answer. they seem to skip the step:

“If prop is “tracks” but the album doesn’t have a “tracks” property, create an empty array before adding the new value to the album’s corresponding property.”

Below is my code, maybe this will be making more sense for you

function updateRecords(id, prop, value) {
 
// If prop isn't "tracks" and value isn't empty (""),
if (prop != "tracks" && value != ""){

 // update or set the value for that record album's property.
   collection[id][prop] = value; 
 }

 // If prop is "tracks" but the album doesn't have a "tracks" property
 if (prop == "tracks" && !collection[id].hasOwnProperty(prop)) {

  // create an empty array before adding the new value to the album's corresponding property.
   collection[id][prop] = []; 
 } 

 // If prop is "tracks" and value isn't empty (""),
 if (prop == "tracks" && value != "") {

 // push the value onto the end of the album's existing tracks array.
collection[id][prop].push(value);
 } 

 // If value is empty (""),
 if (value == "") {

 // delete the given prop property from the album.
   delete collection[id][prop]; 
 } return collection; 
};

I hope this helps :slight_smile:

8 Likes

Thank you for the thorough line by line explanation. Immensely helpful. You rock!! :smile:

I chose to check the value first, then evaluate the prop using a switch. Works, but not the most efficient.

function updateRecords(object, id, prop, value) {
  if (value == "") {
    delete object[id][prop]
  } else {
    switch(prop) {
      case "artist":
        object[id][prop] = value;
        break;
      case "albumTitle":
        object[id][prop] = value;
        break;
      case "tracks":
        if (object[id].hasOwnProperty(prop)) {
          object[id][prop].push(value);
        } else {
          object[id][prop] = [];
          object[id][prop].push(value);
        }
        break;
      default:
        console.log("Invalid Property!");
        break;    
    }
  }
  return object;
}
1 Like