Federico Gentile
Federico Gentile

Reputation: 5940

Query czml/json data in smart way

I am using Cesium and I have a czml file (very similar to JSON format) and I would like to identify one of its elements by specifying the tag of interest:

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
        ]
    }
}];

My goal would be to access a specific element of the variable czml by been able to query the element. For example if I wanted to access the all the data of point B I would like to do it somehow with some function without using any loop possibly (My czml data could be very big!!!).

I was able to achieve my goal like this:

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

But as you can see this is very inefficient. What is a more elegant and efficient way to achieve my goal?

Upvotes: -1

Views: 391

Answers (1)

Serge K.
Serge K.

Reputation: 5323

You can use the find method.

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

Upvotes: 1

Related Questions