0

this seems like it is a very basic question that i can't just can't seem to search properly so i'm going to keep it brief unless someone request otherwise. I have the following javascript function that works,

zipCode.onchange = function () {
var zipPrice = document.getElementById('tripCost');
var zipCity = document.getElementById('cityState')

if ('z'+zipCode.value === 'z39429') { 
    zipPrice.textContent = price$$$$[7].z39429;
    zipCity.textContent = price$$$$[8].z39429;
} else if ('z'+zipCode.value === 'z39483'){
    zipPrice.textContent = price$$$$[7].z39483;
    zipCity.textContent = price$$$$[8].z39483;
}

in which it fills out the city and state info on the form as well as lists a price for the customer to gauge the cost. the two relevant objects in the array contain well over a dozen zip codes however, and i feel like there aught to be a simpler way to do this in which i compare the user input directly to the property rather than manually keying in each input required.

one other note, i put the 'z' with the zip code number because i wasn't sure if my property names could start with a number. if thats no the case the ill change the property names and remove the 'z+' from the function.

M1sf3t
  • 11
  • 3
  • See the dupetarget for details, but: `var key = 'z'+zipCode.value; zipPrice.textContent = price$$$$[7][key]; zipCity.textContent = price$$$$[8][key];` You might want to check if you get `undefined` for either of those, which would mean it's a zip that isn't on the object. – T.J. Crowder Oct 04 '17 at 11:24
  • *"i wasn't sure if my property names could start with a number"* They can, it's perfectly valid for a property name to start with a number: `var obj = {123: "one two three"};` (but don't do that for zipcodes, keep reading). Note that property names are always strings (or Symbols), so that's really `var obj = {"123": "one two three"};`, which is also valid (and essential for zipcodes, since they can start with 0). – T.J. Crowder Oct 04 '17 at 11:26

1 Answers1

0

That code can be refactorized to (removing the 'z'):

zipCode.onchange = function () {
  var zipPrice = document.getElementById('tripCost');
  var zipCity = document.getElementById('cityState');

  zipPrice.textContent = price$$$$[7][zipCode.value];
  zipCity.textContent = price$$$$[8][zipCode.value];
}
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
  • 1
    Why?, you can create an object with numbers as keys, and OP says they added it just in case. Did I misunderstand something else? – Pablo Lozano Oct 04 '17 at 11:24
  • 1
    I'd call out clearly in the answer that you can do that (probably quoting that part of the question) then. But it's a duplicate, so... – T.J. Crowder Oct 04 '17 at 11:25