2013-03-02 79 views
3

Heyho,jQuery的.MAP()返回的對象

我只是建立somekind的地理編碼器的,我需要束JSON映射到後端常規,

試圖映射此UL結構http://jsfiddle.net/PJFVN/1/

<ul id="hiddenmap"> 
<li class="hidden" id="street">Westerwarft 2</li> 
<li class="hidden" id="plz">25859</li> 
<li class="hidden" id="city">Hallig Hooge</li> 
<li class="hidden" id="country" value="" >DE</li> 
<li class="hidden" id="lon" > 8.516472</li> 
<li class="hidden" id="lat" >54.577993</li> 
</ul> 

到地圖看起來像

[{"street":"Westerwarft 2","plz":"25859","location":{"lat":"54.577993","lon":" 8.516472"},"country":"DE"}] 

使用以下JS:

var map = $('#hiddenmap').map(function() { 
var $item = $(this); 
var loc = '{"lat":"'+$item.find('li#lat').text()+'","lon":"'+$item.find('li#lon').text()+'"},'; 
return { 
street: $item.find('li#street').text(), 
plz: $item.find('li#plz').text(), 
location:loc , 
country: $item.find('li#country').text() 
}; 
}).get(); 
var v = JSON.stringify(map); 
alert(v); 

但你可以看到看到小提琴,我的骯髒企圖拋出

[{"street":"Westerwarft 2","plz":"25859","location":"{\"lat\":\"54.577993\",\"lon\":\" 8.516472\"},","country":"DE"}] 

,所以我需要一個原生的方式來獲得地圖內的位置對象, 和persettivly我將需要加入更多的地圖

有沒有辦法做到這一點?

,因爲目前我的鐵桿重複自己,手工建立的地圖爲每個不同的情況下,尋找可怕的,如:

 var String = '['+'{'+'"fax":'+'"'+fax1+'"'+','+'"genau":'+genau1+','+'"land":'+'"'+land1+'"'+','+'"location": {'+'"lon":'+lon1+','+'"lat":'+lat1+'},'+'"notruf":'+'"'+notruf1+'"'+','+'"ort":'+'"'+ort1+'"'+','+'"plz":'+'"'+plz1+'"'+','+'"strasse":'+'"'+strasse1+'"'+','+'"telefon":'+'"'+telefon1+'"},{'+'"fax":'+'"'+fax2+'"'+','+'"genau":'+genau2+','+'"land":'+'"'+land2+'"'+','+'"location": {'+'"lon":'+lon2+','+'"lat":'+lat2+'},'+'"notruf":'+'"'+notruf2+'"'+','+'"ort":'+'"'+ort2+'"'+','+'"plz":'+'"'+plz2+'"'+','+'"strasse":'+'"'+strasse2+'"'+','+'"telefon":'+'"'+telefon2+'"}]'; 

我需要提前擺脫這個

感謝任何暗示

回答

8

也許我沒有正確理解您的問題,但我不確定您是否正在爲該位置手動構建字符串。你爲什麼不把它作爲本地對象,讓JSON.stringify()處理轉換。

像這樣:

var map = $('#hiddenmap').map(function() { 
    var $item = $(this); 
    var loc = { 
     lat: $item.find('li#lat').text(), 
     lon: $item.find('li#lon').text() 
    }; 
    return { 
     street: $item.find('li#street').text(), 
     plz: $item.find('li#plz').text(), 
     location: loc, 
     country: $item.find('li#country').text() 
    }; 
}).get(); 
var v = JSON.stringify(map); 
console.log(v); 
alert(v); 
+0

耶的作品,非常感謝。我的大腦只是看着我一年前做了什麼,使它儘可能複雜 – 2013-03-02 12:10:19

2

只是將loc變量定義爲真正的JSON映射而不是表示JSON映射的字符串:http://jsfiddle.net/PJFVN/2/

jQuery(document).ready(function ($) { 
    $('#action').click(function() { 
     var map = $('#hiddenmap').map(function() { 
      var $item = $(this); 
      var loc = {lat : $item.find('li#lat').text(), 
         lon : $item.find('li#lon').text()}; 
      return { 
       street: $item.find('li#street').text(), 
       plz: $item.find('li#plz').text(), 
       location: loc, 
       country: $item.find('li#country').text() 
      }; 
     }).get(); 
     var v = JSON.stringify(map); 
     alert(v); 
    }); 
}); 
+0

非常感謝工作正常 – 2013-03-02 12:11:04