简体   繁体   中英

how to call an array of keys from an array of objects?

If I have the following array

someArray = [{id: 1, coordinates: {latitude: 1212, longitude: 13324}},{id: 2, coordinates: {latitude: 1314, longitude: 15151}}]

is there anyway to call someArray so I get just the array of the coordinates keys without having to make a new array? someArray.coordinates gives me undefined. Expected output:

[{latitude: 1212, longitude: 13324}, {latitude: 1314, longitude: 15151}] 

You can use Array#map ( spec , MDN ) for that:

someArray = someArray.map(function(entry) {
    return entry.coordinates;
});

Array#map produces a new array from the entries you return from the iteration function you pass into it.

Live Example :

 var someArray = [{id: 1, coordinates: {latitude: 1212, longitude: 13324 }}, {id: 2, coordinates: {latitude: 1314,longitude: 15151}}]; snippet.log("Before:"); snippet.log(JSON.stringify(someArray)); someArray = someArray.map(function(entry) { return entry.coordinates; }); snippet.log("After:"); snippet.log(JSON.stringify(someArray));
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

You can try with a map function:

someArray.map(function(current, index, array){ array[index] = current.coordinates});

This will, though, modify your original. You can get it as another array like:

var coordinates = [];
someArray.map(function(current){coordinates.push(current.coordinates)});

And yes, sorry, I forgot, the easiest is:

var coordinates = someArray.map(function(current) { return current.coordinates; });

Or you can write it yourself:

function getCoordinates(objectArray) {
   var coordinates = [];
   for (var i in objectArray) {
      var current = objectArray[i];
      coordinates.push(current.coordinates);
   }
}

var onlyCoordinates = getCoordinates(someArray);

EDITED: Just use following snippet

 var someArray = [{id: 1, coordinates: {latitude: 1212, longitude: 13324}},{id: 2, coordinates: {latitude: 1314, longitude: 15151}}]; var i = -1; while(someArray[++i]){ someArray[i] = someArray[i].coordinates; } document.write("<pre>"+JSON.stringify(someArray,0,3)+"</pre>");

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