【发布时间】:2017-02-16 06:23:31
【问题描述】:
我是一名 R 程序员,我认为 javascript 中的数组类似于 R 中的列表。在 R 中,当我想访问列表的元素时,我会使用 lapply() 和 do.call 将函数应用于内部元素,然后将结果放入新的数据结构中。我在 javascript 中读到了 map 函数,但我似乎无法破解它:
data = {"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "CRS" } },
"features": [
{ "type": "Feature",
"id": 6,
"properties": {"species": "giraffe",
"result": 0,
"popup_text": "Some text" },
"geometry": { "type": "Point", "coordinates": [ 1, 5] } },
{ "type": "Feature",
"id": 7,
"properties": { "species": "pig",
"result": 0,
"popup_text": "Some text" },
"geometry": { "type": "Point", "coordinates": [ 2,3 ] } },
{ "type": "Feature",
"id": 8,
"properties": { "species": "goat",
"result": 0,
"popup_text": "Some Text" },
"geometry": { "type": "Point", "coordinates": [ 1,6 ] } },
{ "type": "Feature",
"id": 16,
"properties": { "species": "giraffe",
"result": 0,
"popup_text": "Some Text" },
"geometry": { "type": "Point", "coordinates": [ 3,4 ] } },
{ "type": "Feature",
"id": 18,
"properties": { "species": "pig",
"result": 0,
"popup_text": "Some Text" },
"geometry": { "type": "Point", "coordinates": [ 2,7 ] } }
]
}
所以,data.features 是一个包含 5 个元素的数组,每个元素包含 4 个数组:type、id、properties、geometry。我想生成一个只是 properties.result 值的新数组。它的结构是这样的:
newdata = [0, 0, 0, 0, 0]
到目前为止,我尝试了以下方法,但没有得到我想要的结果:
var result = data.features.map(function(i) {
return{
result: i.properties.result
};
});
console.log(result)
有什么想法可以做到这一点吗?最后我的目的是确定any 的result == 1
【问题讨论】:
-
如果你想返回一个数字 - 返回一个数字:
return i.properties.result;
标签: javascript multidimensional-array array.prototype.map