简体   繁体   中英

Map dynamic key to values in Javascript array

I need to map one object array into this format:

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

where my source array looks like

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

I can't figure out how to make place be the key of the array.

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

is obviously wrong.

Iterate over the array, add each value to the object and delete the place property:

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

Try:

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

What is the expected result?

Maybe:

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

I assume you have an array of objects? If so, this will work (assuming you are using underscorejs based on _.map()):

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

This will give you an object where the key is the place and the associated values are themselves objects containing the latitude and longitude.

You might try using obj.map() and re-map all the elements.

Here is an example:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM