我正在使用Cesium并且我有一个czml文件(非常类似于json格式),我想通过指定感兴趣的标记来识别其中一个元素:
var czml = [{
"id" : "document",
"name" : "Basic CZML billboard and label",
"version" : "1.0"
}, {
"id" : "Point A",
"name" : "Point A",
"label" : {
"fillColor" : {
"rgba" : [255, 255, 255, 255]
},
"font" : "12pt Lucida Console",
"text" : "Point A",
},
"position" : {
"cartographicDegrees":[
0, 0, 0
]
}
}, {
"id" : "Point B",
"name" : "Point B",
"label" : {
"fillColor" : {
"rgba" : [255, 255, 255, 255]
},
"font" : "12pt Lucida Console",
"text" : "Point B",
},
"position" : {
"cartographicDegrees":[
10, 10, 0
]
}
}];
我的目标是通过查询元素来访问变量czml的特定元素。例如,如果我想访问point B
的所有数据,我想以某种方式使用某些函数而不使用任何循环(我的czml数据可能非常大!!!)。
我能够实现这样的目标:
for (var i=0; i<3; i++) {
if (czml[i].id === "Point B") {
console.log(czml[i].id);
console.log(czml[i].name);
console.log(czml[i].label.text);
console.log(czml[i].position.cartographicDegrees) ;
}
}
但是你可以看到这是非常低效的。什么是实现我的目标的更优雅和有效的方式?
答案 0 :(得分:1)
您可以使用find方法。
var czml = [{
"id": "document",
"name": "Basic CZML billboard and label",
"version": "1.0"
}, {
"id": "Point A",
"name": "Point A",
"label": {
"fillColor": {
"rgba": [255, 255, 255, 255]
},
"font": "12pt Lucida Console",
"text": "Point A",
},
"position": {
"cartographicDegrees": [
0, 0, 0
]
}
}, {
"id": "Point B",
"name": "Point B",
"label": {
"fillColor": {
"rgba": [255, 255, 255, 255]
},
"font": "12pt Lucida Console",
"text": "Point B",
},
"position": {
"cartographicDegrees": [
10, 10, 0
]
}
}];
var point = czml.find((e) => e.id === 'Point B');
console.log(point);