以智能方式查询 czml/json 数据

Query czml/json data in smart way

我正在使用 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) ;      
    }
}

但是如您所见,这是非常低效的。什么是更优雅、更有效的方式来实现我的目标?

您可以使用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);