Record Collection JS challenge

Replacing :
else if (prop == “tracks” && value != “”)
for that:
else if (records[id].hasOwnProperty(“tracks”) && value != “”)

?

That won’t quite work. You still need to check if you are handling the tracks property.

It helps if you show your entire code each time because the order of the if-else clauses matters greatly.

Oh ok, I’ll show the entire code.

function updateRecords(records, id, prop, value) {
  if (prop != "tracks" && value != "") {
  records[id][prop] = value;
} else if (prop == "tracks") {
  records[id][prop] = [value];
} else if (records[id].hasOwnProperty("tracks") && value != "") {
  records[id][prop].push(value); 
} else if (value == ""){
  delete records[id][prop];
}
  
  return records;
}
updateRecords(recordCollection, 5439, 'artist', 'ABBA');

So, yes, I can see that it’s not what I’m supposed to do.

Nothing yet, still trying.

hmmm… you want to create an array if the “tracks” don’t exist, right?

So, in the second conditional, prop should be undefined?

function updateRecords(records, id, prop, value) {
  if (prop != "tracks" && value != "") {
  records[id][prop] = value;
} else if (prop == undefined) {
  records[id][prop] = [value];
} else if (records[id].hasOwnProperty("tracks")  && value != "") {
  records[id][prop].push(value); 
} else if (value == ""){
  delete records[id][prop];
}
  
  return records;
}
updateRecords(recordCollection, 5439, 'artist', 'ABBA');

I don’t know what I said that implied that, but no.

How do you check if a property exists again?

records[id].hasOwnProperty()

Right, and you should pair creating the new array with the case where you don’t have the tracks property.

I finally got it!!!

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

updateRecords(recordCollection, 5439, 'artist', 'ABBA');

Thanks a lot for all the help. I really appreciate that.

Good job getting it working! You can tidy it up a bit by using === instead of == and !== instead of !=.

Oh ok, I wasn’t sure if would make too much of a difference, thanks for letting me know.

== is a weak comparison, so Javascript converts to the same type on each side. The conversion rules can be surprising. It is better to use === where does not convert types.

So sticking with === and !== will help to avoid broken code.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.