0

I am very new to node.js.

I have a JSON that I am reading from a website. Without posting too much of the JSON, here's roughly what I'm looking at:

{
   "Head": {
      "Front": "80",
      "Side": "85",
      "Back": "75"
   },
   "Neck": {
      "Front": "65",
      "Side": "70",
      "Back": "60"
   }
}

I have a function that is formatted the following way:

function whichBodyPart(part, file, time) {
      var fileParse = JSON.parse(file);
      var type;
      switch(time.toLowerCase()){
        case ('9AM'):
            type = 'Front';
        break;
        case ('12PM'):
            type = 'Side';
        break;
        case ('3PM'):
            type = 'Back';
        break;
    }
    return fileParse.part.type;
  }

part is a user-passed-in value that, in this case, would either be "Head" or "Neck"

file is the un-parsed JSON file. I parse it in the function.

I know that to pull a specific element's value out of the JSON file I have here, I could do something along the lines of

return fileParse.Head.Back

and that would give me back the value "75". However, what I'm trying to do is navigate the JSON with the values from the variables part and type.

For example, if part is "Neck" and type is "Side", I want to retrieve the value "70" from the JSON. However, if the user input part as "Head" and type is "Front", I want to receive "80".

How do I make the return able to handle varying inputs?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Hiro
  • 1
  • 1
  • use the bracket notation `fileParse[part][type]` – njzk2 Jan 16 '20 at 06:56
  • Does this answer your question? [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) and [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Patrick Roberts Jan 16 '20 at 07:00
  • Thank you guys. I was unaware of this notation and for some reason couldn't find it specifically. I figured something had to exist to handle this. – Hiro Jan 16 '20 at 07:27

1 Answers1

1

You may use bracket notation of JavaScript to handle your varying inputs. Try:

return fileParse[part][type]
Guney Cobanoglu
  • 733
  • 1
  • 6
  • 20
  • Thank you! I'm not sure why I couldn't find this syntax. Probably wasn't wording it correctly on Google. But I got it working :) – Hiro Jan 16 '20 at 07:28