如何创建JavaScript对象并动态填充数据?

时间:2019-08-26 14:15:21

标签: javascript arrays json object

我想使用键值对动态创建数据对象。在该对象中,还有一个名为要素的数组,并且在这个称为几何的数组元素中还有一个数组坐标。

在要素数组中,标题和内容之类的属性将动态添加,并且还会添加坐标数组的值。

如何在坐标数组中添加数据:“ geometryy”:{“ coordinates”:[]} ..?

data = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": {
        "title": "Day 1",
        "content": "This is where some people moved to."
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -73.7949,
          40.7282,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "The Next Day",
        "content": "This is where some people grooved to."
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -74.3838,
          40.9148,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "Amazing Event",
        "content": "This is where they went to have fun."
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          4.899431,
          52.379189,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "1776",
        "content": "This where they went when the revolution had begun."
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -71.3489484,
          42.4603719,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "1776",
        "content": "This where they went when the revolution had begun."

      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -71.2272,
          42.4473,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "1984",
        "content": "So they all came here...and disappeared without a trace!"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -0.118092,
          51.509865,
          1
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "title": "12/22/63",
        "content": "Now, this can be quite the scary place."
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -70.2553259,
          43.661471,
          1
        ]
      }
    },
  ]
}

var data = {

    features: []
    };
    for (piece in pieces){

     data.features.push({
            type: "Feature",
            properties: {title: '{piece.title}' , content: '{piece.content}' },
            geometry: {type: "Point"},

   });

  }

1 个答案:

答案 0 :(得分:1)

您已经尝试过什么?问题出在哪里? 您可以执行以下操作:

var data = {
    features: []
};

data.features.push({
    type: "Feature"
});