[英]NodeJS: How to add a variable to the return for a JSON.parse()?
I am very new to node.js.我对 node.js 很陌生。
I have a JSON that I am reading from a website.我有一个正在从网站上读取的 JSON。 Without posting too much of the JSON, here's roughly what I'm looking at:
在没有发布太多 JSON 的情况下,这大致是我在看的内容:
{
"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" part是用户传入的值,在这种情况下,它可以是“Head”或“Neck”
file is the un-parsed JSON file. file是未解析的 JSON 文件。 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我知道要从这里的 JSON 文件中提取特定元素的值,我可以执行以下操作
return fileParse .返回 fileParse 。 Head.Back
返回
and that would give me back the value "75".这会让我返回值“75”。 However, what I'm trying to do is navigate the JSON with the values from the variables part and type .
但是,我想要做的是使用变量part和type 中的值导航JSON。
For example, if part is "Neck" and type is "Side", I want to retrieve the value "70" from the JSON.例如,如果part是“Neck”, type是“Side”,我想从 JSON 中检索值“70”。 However, if the user input part as "Head" and type is "Front", I want to receive "80".
但是,如果用户输入部分为“Head”并且类型为“Front”,我想收到“80”。
How do I make the return able to handle varying inputs?我如何使退货能够处理不同的输入?
You may use bracket notation of JavaScript to handle your varying inputs.您可以使用 JavaScript 的括号表示法来处理不同的输入。 Try:
尝试:
return fileParse[part][type]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.