如何从对象数组中调用键数组?

时间:2015-09-01 16:54:20

标签: javascript arrays node.js

如果我有以下数组

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

无论如何都要调用someArray所以我只得到坐标键的数组而不必创建一个新的数组? someArray.coordinates给了我undefined。 预期产出:

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

3 个答案:

答案 0 :(得分:3)

您可以使用Array#mapspecMDN):

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

Array#map从您传入迭代函数的条目中生成一个新数组。

直播示例



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>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您可以尝试使用地图功能:

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

但是,这将修改您的原件。您可以将其作为另一个数组来获取:

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

是的,抱歉,我忘了,最简单的是:

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

或者你可以自己写一下:

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

var onlyCoordinates = getCoordinates(someArray);

答案 2 :(得分:-3)

已编辑:只需使用以下代码段

即可

&#13;
&#13;
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>");
&#13;
&#13;
&#13;