简体   繁体   中英

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

In javascript, is there a way to treat a JSON keyname as a variable?

For instance, below I want to perform (any set of actions) on the value of a different key in JSON each time, by telling it which json key to get by feeding the keyname to the function as a parameter.

The basic idea here is: Make a function to do (x) no matter what JSON it's given. I just need to tell it what key I want.

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". 

Is this possible? How do get the function to assign the VALUE of the string I'm building with the parameter, rather than just the string as "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 

or you can access to global context using "this" keyword and variable name (instead variable identifier == reference)

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 

Yes you can do it. You can get the JSON value like this:

jsonName.variableKeyName;

but you can also get it like this:

jsonName["variableKeyName"];

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

So you can change your code in this way:

 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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