2013-01-11 140 views
0
var Data = { "1":"United States", 
       "2":"United Kingdom", 
       "3":"Aruba", 
       "4":"United Kingdom", 
       "5":"Aruba", 
       "6":"Bahrain", 
       "7":"United Kingdom", 
       "8":"Algeria", 
       "9":"Andorra", 
       "10":"American Samoa" 
} 
var IdKeyValuePair = [{"DropD1":Data},{"DropD2":Data},{"DropD3":Data},{"DropD4":Data}]; 
var obj= { 
      id   : IdKeyValuePair, 
      MultiColuumn : true, 
      Checkbox  : true, 
      Pagination : false, 
      max_height : 400 

     }; 

我想打印DropD1,DropD2的名稱.. 我試着以這種方式。但我無法做到這一點..如何將json對象名稱轉換爲字符串格式

var idName = [],i; 
idLen = obj.id.length; 
for(i=0;i<idLen;i++){ 
    idName[i] = ''+obj.id[i]; 
    console.log(idName[i]); 
} 

我收到DropD1,DropD2 ..但問題是,它在一個對象表格,以便我怎樣才能將它轉換字符串中的... 我想結果是這樣的格式...

for(i=0;i<idLen;i++){ 
    console.log(idName[i]); 
} 

字符串格式的預期輸出沒有對象:

DropD1 DropD2 DropD3

+0

的可能重複的對象轉換爲字符串[我如何找到這個Json對象的長度](http://stackoverflow.com/questions/14272416/how-can-i-find-the-length-of-this-json-object) - 考慮閱讀你的答案以前的問題,因爲他們都顯示瞭如何迭代一個屬性目的。當你在這裏 - 評論/接受答案。 –

+0

http://stackoverflow.com/questions/1876485/get-property-names-in-json-objects –

回答

0

我使用的瀏覽器字符串化屬性::有一個解決方案

var jsonobj={"name":"George", "age":29, "friends":["John", "Sarah", "Albert"]} 
var jsonstr=JSON.stringify(jsonobj) 
alert(typeof jsonstr) //string 

U可以將其轉換爲JavaScript對象以下列方式::

var jsonstr='{"name":"George", "age":29, "friends":["John", "Sarah", "Albert"]}' 
var george=JSON.parse(jsonstr) //convert JSON string into object 
alert(george.age) 

欲瞭解更多信息關於json請參考以下鏈接,

http://www.javascriptkit.com/jsref/json.shtml

0

嘗試。它的工作對我來說

var IdKeyValuePair = [{ "DropD1": Data["1"] }, { "DropD2": Data["2"] }, { "DropD3": Data["3"]}, { "DropD4": Data["4"]}]; so on and so forth. 
0

嘗試此

var idName = [],i; 
idLen = obj.id.length; 
for(i=0;i<idLen;i++){ 
    idName[i] = obj.id[i]; 
} 
console.log(idName.join(" ")); 
0

嘗試這種情況:

var Data = { "1":"United States", 
        "2":"United Kingdom", 
        "3":"Aruba", 
        "4":"United Kingdom", 
        "5":"Aruba", 
        "6":"Bahrain", 
        "7":"United Kingdom", 
        "8":"Algeria", 
        "9":"Andorra", 
        "10":"American Samoa" 
    } 
    var IdKeyValuePair = [{"DropD1":Data},{"DropD2":Data},{"DropD3":Data},{"DropD4":Data}]; 
    var obj= { 
       id   : IdKeyValuePair, 
       MultiColuumn : true, 
       Checkbox  : true, 
       Pagination : false, 
       max_height : 400 

      }; 

    var idName = [],i; 
    idLen = obj.id.length; 
    for(i=0;i<idLen;i++){ 
    idName[i] = obj.id[i]; 
    console.info(JSON.stringify(idName[i])); 
    } 

你被不必要地通過添加空字符串的對象( 「」 +對象)

相關問題