Wie

2012-11-20 12 views
15

Mögliche Duplizieren in einem JSON-Objekt ein String-Variable als Schlüssel verwenden:
Is a way that use var to create JSON object in key?Wie

Ich mag unter Verwendung des Werts eines ein JSON-Objekt in JavaScript konstruieren (String) Variable als Schlüssel. Aber was ich bekam, ist der Name der Variable als Schlüssel.

example.js:

function constructJson(jsonKey, jsonValue){ 
    var jsonObj = { "key1":jsonValue, jsonKey:2}; 
    return jsonObj; 
} 

Der Aufruf

constructJson("key2",8); 

eine JSON zurückgibt -> { "key1": 8, "jsonKey": 2} aber ich haben möchte {“ Schlüssel1 ": 8," Schlüssel2 ": 2}.

Weiß jemand, wie man das erreicht? scheint wie ein einfaches Problem, aber ich kann nicht die Lösung

thx im Voraus, ronny

+0

leid für doppelte Frage ... gefunden awnser finden Sie hier: http://stackoverflow.com/a/882749/1005072 – rontron

Antwort

33
function constructJson(jsonKey, jsonValue){ 
    var jsonObj = {"key1": jsonValue}; 
    jsonObj[jsonKey] = "2"; 
    return jsonObj; 
}