0

I have been following a JavaScript course (freeCodeCamp) on Youtube Timestamp:02:03:06. Before following up with their solution I made my own attempt. In the project, I am supposed to create a function updateRecords that adds information to the records of a "collection" object following this criteria:

  1. If property to be added to record is an empty string value, delete the property
  2. If it already has a value, update the old value to new value.
  3. If the update property is a track/song, add that to the track list.

I am getting this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
at updateRecords (updateFunction.js:33:23)
at updateFunction.js:52:13

Here's my initial attempt:

var collection = {
  "2548": {
    "album": "Slippery When Wet",
    "artist": "Bon Jovi",
    "tracks": [
      "Let It Rock",
      "You Give Love A Bad Name"
    ]
  },
  "2468": {
    "album": "1999",
    "artist": "Prince",
    "tracks": [
      "1999",
      "Little Red Corvette"
    ]
  },
  "1245": {
    "artist": "Robert Palmer",
    "tracks": []
  },
  "5439": {
    "album": "ABBA Gold"
  }
};

var collectionCopy = JSON.parse(JSON.stringify(collection));

function updateRecords(id, prop, value) {
  //update property for existing record
  //add track to record
  if (prop === "tracks") {
    if (collection.id.hasOwnProperty("tracks")){
        collection.id.tracks.push(value);
    } else {
      collection.id.tracks = [value];
    }
  } else {
      if (collection.hasOwnProperty(id)) {
        //update the record property only if the record update property isn't an empty string
        if (value !== undefined) {
          collection.id[prop] = value;
        } else {
          delete collection.id.prop;
        }  
      }
    }
    return collection;
  }


console.log(updateRecords("5439", "tracks", "Take a chance on me"))
  • The error means when you access `collection.id.hasOwnProperty("tracks")`, `collection.id` is `undefined`. That's because you need `collection[id].hasOwnProperty("tracks")` instead so you use the variable value and not literally "id". –  Aug 09 '22 at 19:23
  • 1
    Duplicate: [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) –  Aug 09 '22 at 19:25
  • 1
    Hi there. I'm one of the moderators at freeCodeCamp. We have a large community and even a Discord where you can ask help with problems you encounter in our curriculum and / or our videos. I highly recommend you use them instead of Stack Overflow as the questions are usually not on topic for Stack Overflow and writing half a book to properly teach you is not the purpose of SO – icecub Aug 09 '22 at 19:26

0 Answers0