title: I am trying to push a value to an array only if the array exists within a javascript object. If the array doesn't exist, I wish to create one and add
body: <p>I have been following a JavaScript course (freeCodeCamp) on <a href="https://www.youtube.com/watch?v=PkZNo7MFNFg&amp;t=236s" rel="nofollow noreferrer">Youtube</a> 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 &quot;collection&quot; object following this criteria:</p>
  <ol>
  <li>If property to be added to record is an empty string value, delete the property</li>
  <li>If it already has a value, update the old value to new value.</li>
  <li>If the update property is a track/song, add that to the track list.</li>
  </ol>
  <p>I am getting this error:</p>
  <pre><code>Uncaught TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
  at updateRecords (updateFunction.js:33:23)
  at updateFunction.js:52:13
  </code></pre>
  <p>Here's my initial attempt:</p>
  <pre><code>var collection = {
    &quot;2548&quot;: {
      &quot;album&quot;: &quot;Slippery When Wet&quot;,
      &quot;artist&quot;: &quot;Bon Jovi&quot;,
      &quot;tracks&quot;: [
        &quot;Let It Rock&quot;,
        &quot;You Give Love A Bad Name&quot;
      ]
    },
    &quot;2468&quot;: {
      &quot;album&quot;: &quot;1999&quot;,
      &quot;artist&quot;: &quot;Prince&quot;,
      &quot;tracks&quot;: [
        &quot;1999&quot;,
        &quot;Little Red Corvette&quot;
      ]
    },
    &quot;1245&quot;: {
      &quot;artist&quot;: &quot;Robert Palmer&quot;,
      &quot;tracks&quot;: []
    },
    &quot;5439&quot;: {
      &quot;album&quot;: &quot;ABBA Gold&quot;
    }
  };
  
  var collectionCopy = JSON.parse(JSON.stringify(collection));
  
  function updateRecords(id, prop, value) {
    //update property for existing record
    //add track to record
    if (prop === &quot;tracks&quot;) {
      if (collection.id.hasOwnProperty(&quot;tracks&quot;)){
          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(&quot;5439&quot;, &quot;tracks&quot;, &quot;Take a chance on me&quot;))
  </code></pre>