2015-06-09 25 views
0

我需要一个对象数组映射成这种格式:地图动态关键值

   "Brandenburg Gate, Berlin": {latitude: 52.516272, longitude: 13.377722}, 
      "Dortmund U-Tower": {latitude: 51.515, longitude: 7.453619}, 
      "London Eye": {latitude: 51.503333, longitude: -0.119722}, 
      "Kremlin, Moscow": {latitude: 55.751667, longitude: 37.617778}, 
      "Eiffel Tower, Paris": {latitude: 48.8583, longitude: 2.2945}, 
      "Riksdag building, Stockholm": {latitude: 59.3275, longitude: 18.0675}, 
      "Royal Palace, Oslo": {latitude: 59.916911, longitude: 10.727567} 
      } 

在我的源阵列看起来像

{place: "Brandenburg Gate, Berlin", latitude: 52.5, longitude 13.3 } 

我无法弄清楚如何使place成为该阵列的关键。

_.map(a, function (m) {return m.place: {longitude: m.longitude}}) 

显然是错误的。

+0

你确定这是一个数组?它看起来像JSON – beautifulcoder

+0

@beautifulcoder:绝对不是JSON,以及数据如何被接收/编码与问题无关。 –

回答

2

迭代这个数组,每个值添加到对象并删除place属性:

var obj = {}; 
arr.forEach(function(value) { 
    obj[value.place] = value; 
    delete value.place; 
}); 
+0

谢谢 - 我永远不会想到这样做。 – metalaureate

1

预期结果是什么?

可能:

_.map(a, function (m) { 
    return {"place":m.place, "longitude": m.longitude} 
}) 
0

我假设你有对象的数组?如果是这样,这将工作(假设你使用基于_.map underscorejs()):

var locationObject = {}; 
_(arrayOfLocations).each(function(location) { 
    locationObject[location.place] = { latitude: location.latitude, longitude: location.longitude }; 
}); 

这会给你一个对象,其中的关键是地方和相关的值是包含纬度自己的对象和经度。

2

尝试:

var result = {}; 
a.forEach(function (item) { 
    result[item.place] = {longitude: item.longitude, latitude: item.latitude}; 
}); 
0

您可以尝试使用obj.map()和重新映射的所有元素。

下面是一个例子:

<script type="text/javascript"> 
function experiment() { 
var obj = [{place: "Brandenburg Gate, Berlin", latitude: 52.5, longitude: 13.3}, 
     {place: "Dortmund U-Tower", latitude: 51.515, longitude: 7.453619}, 
     {place: "London Eye", latitude: 51.503333, longitude: -0.119722}]; 

/* Mapped Output 
"Brandenburg Gate, Berlin": {latitude: 52.516272, longitude: 13.377722}, 
"Dortmund U-Tower": {latitude: 51.515, longitude: 7.453619}, 
"London Eye": {latitude: 51.503333, longitude: -0.119722}, 
*/ 

// create a new object array 
var reformattedArray = obj.map(function(o){ 
    var rObj = {}; 
    rObj[o.place] = {latitude : o.latitude, longitude : o.longitude}; 
    return rObj; 
}); 
} 
window.onload = experiment; 
</script>