繁体   English   中英

JAVASCRIPT:将json键名作为参数传入,通过参数获取值

[英]JAVASCRIPT: pass json key's name as parameter, and use the parameter to get the value

在 javascript 中,有没有办法将 JSON 键名视为变量?

例如,下面我想每次对 JSON 中不同键的值执行(任何一组操作),通过将键名作为参数提供给 function 来告诉它要获取哪个 json 键。

这里的基本思想是:使 function 做 (x) 无论它给出什么 JSON。 我只需要告诉它我想要什么钥匙。

var myObj = {name: "John", age: 31}; // dataset #1
var myObj2 = {month: "January", day: 20}; //dataset #2

function myFunction(jsonName, variableKeyName) {   

  var variableKeyValue = jsonName + "." + variableKeyName;  //wrong way to do this, apparently.
 
  console.log(variableKeyValue); 
}

myFunction("myObj", "name"); //want this to log "John", not the string "myObj.name".
myFunction("myObj2", "day"); //want this to log "20", not the string "myObj2.day". 

这可能吗? 如何让 function 分配我正在使用参数构建的字符串的值,而不仅仅是字符串“jsonNameX.variableKeyNameX”?

const myObj = {name: "John", age: 31}; // dataset #1
const myObj2 = {month: "January", day: 20}; //dataset #2

function myFunction(json, variableKeyName) {   
  const variableKeyValue = json[variableKeyName]; 
  console.log(variableKeyValue); 
}

myFunction(myObj, "name"); // this log "John"
myFunction(myObj2, "day"); // this log 20 

或者您可以使用“this”关键字和变量名(而不是变量标识符 == 引用)访问全局上下文

const myObj = {name: "John", age: 31}; // dataset #1
const myObj2 = {month: "January", day: 20}; //dataset #2

function myFunction(jsonName, variableKeyName) {   
  const variableKeyValue = this[jsonName][variableKeyName]; 
  console.log(variableKeyValue); 
}

myFunction("myObj", "name"); // this log "John"
myFunction("myObj2", "day"); // this log 20 

是的,你可以做到。 您可以像这样获得 JSON 值:

jsonName.variableKeyName;

但你也可以这样得到它:

jsonName["variableKeyName"];

( https://www.w3schools.com/js/js_json_syntax.asp )

所以你可以这样改变你的代码:

 var myObj = {name: "John", age: 31}; // dataset #1 var myObj2 = {month: "January", day: 20}; //dataset #2 function myFunction(jsonName, variableKeyName) { var variableKeyValue = jsonName[variableKeyName]; console.log(variableKeyValue ); } myFunction(myObj, "name"); //this prints "John" myFunction(myObj2, "day"); //this prints "20"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM