修改服务字段类型

背景

接口返回的是geojson格式,但是使用GeojsonLayer加载的时候,高亮的坐标有问题。排查发现,是接口返回的坐标全是string类型。

所以要写一个方法,把string类型的坐标转换为double类型,其他的数据保持不变。

转换的格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"ID": "1"
},
"geometry": {
"type": "Point",
"coordinates": [
"120.98058226222103",
"31.19176762858661"
]
}
},
{
"type": "Feature",
"properties": {
"ID": "5"
},
"geometry": {
"type": "Point",
"coordinates": [
"121.0442694",
"31.27477222"
]
}
}
]
}
->
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"ID": "1"
},
"geometry": {
"type": "Point",
"coordinates": [
120.98058226222103,
31.19176762858661
]
}
},
{
"type": "Feature",
"properties": {
"ID": "5"
},
"geometry": {
"type": "Point",
"coordinates": [
121.0442694,
31.27477222
]
}
}
]
}

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ramda</title>

<style>
textarea {
width: 100%;
}
</style>
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>
</head>

<body onload="workFlow()">
<textarea cols="100" rows="50"></textarea>

<script>
const getResponse = () => {
return {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"ID": "1",
},
"geometry": {
"type": "Point",
"coordinates": [
"120.98058226222103",
"31.19176762858661"
]
}
},
{
"type": "Feature",
"properties": {
"ID": "5",
},
"geometry": {
"type": "Point",
"coordinates": [
"121.0442694",
"31.27477222"
]
}
}
]
};
}

const workFlow = () => {
const response = getResponse();
const featuresLens = R.lensProp('features'); // 使用透镜获取features属性
const coordinatesLens = R.lensPath(['geometry', 'coordinates']); // 使用透镜获取coordinates属性
const coordinates2num = R.map(Number); // 把坐标值从字符串转为数字
const overFeatures = R.over(coordinatesLens, coordinates2num); // 修改features中coordinates的值
const mapFeatures = R.map(overFeatures); // 遍历features
const overResponse = R.over(featuresLens, mapFeatures); // 修改response中features的值
const result = overResponse(response);
print(response);
}

// 打印结果相关
const setTextarea = str => {
document.getElementsByTagName("textarea")[0].value = str;
};

const stringify = json => JSON.stringify(json, null, " ");

const print = R.compose(
setTextarea,
stringify
);
// 打印结果相关
</script>
</body>

</html>

结束语

按平时ES6的写法,循环遍历,然后修改值。破坏了数据不变。

ramda的写法明显要更复杂一些。