将动态键映射到Javascript数组中的值

时间:2015-06-09 02:02:51

标签: javascript

我需要将一个对象数组映射到这种格式:

             "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}})

显然是错误的。

5 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

尝试:

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

答案 2 :(得分:1)

预期结果是什么?

也许:

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

答案 3 :(得分:0)

我假设你有一个对象数组?如果是这样,这将起作用(假设您使用基于_.map()的下划线):

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

这将为您提供一个对象,其中键是位置,关联值本身就是包含纬度和经度的对象。

答案 4 :(得分: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>