Javascript Json object, get value by key string. Ex: GetMyVal (MyKeyInString)

I have this json info:

data.ContactName data.ContactEmal data.Departement 

I would like to have such a function

 function GetMyVal(myStringKey) { $.Ajax ,... , ... ,success :function(data) { $("#mytarget").val(data.myStringKey); } } 

Call Like This GetMyVal("ContactName");

+4
source share
3 answers

Decision:

Try changing:

 $("#mytarget").val(data.myStringKey); 

in

 $("#mytarget").val(data[myStringKey]); 

Explanation:

Here is what these constructs mean:

$("#mytarget").val(SOMETHING);
change element value from id "mytarget" to SOMETHING

data.myStringKey
take an object called "data" and give me the value of its property with the name literally "myStringKey"

data[myStringKey]
take an object called "data" and give me the value of its property, named as the value of a variable called "myStringKey"

+5
source

You can use something like this:

  $('#mytarget').val(data[myStringKey]); 

In JavaScript construction:

  reference_to_object [ expression ] 

means evaluate the expression and then use its string value as the name of the property to search for the property in the specified object.

+3
source

Just do the following:

 $("#mytarget").val(data[myStringKey]); 
+3
source

Source: https://habr.com/ru/post/1343331/


All Articles