-1

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

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

4

1 回答 1

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);

于 2017-07-24T12:07:47.053 回答