簡體   English   中英

動態創建對象字面量

[英]Dynamically creating Object literal

我正在嘗試在名為“features”的對象數組中動態添加一個名為“geometry”的對象及其屬性“x”和“y”。 假設 for循環運行 N次而不是 2 次。
我想要實現的最終結構是這樣的:

{
  "type": "features",
  "features": [{
      "geometry": {
          "x": -8.895197546558027,
          "y": 38.52577703769191
      }
  },
  {
      "geometry": {
          "x": -8.877264297084386,
          "y": 38.53907316236277
      }
  }]
}

使用代碼我收到錯誤 - “無法設置未定義的屬性'幾何'”。

function makeOrders(){
    try {
        var orders = { "type": "features" };
        orders.features = [{}];
        for(var i=0; i<2; i++){
            orders.features[i].geometry = {};
            orders.features[i].geometry.x = "value_here";
            orders.features[i].geometry.y = "other_value_here";
        }
        console.log(orders);
    } catch (e) {
        console.error(e);
    }
}
orders.features = [{}];

features是一個數組。 索引0處的值(最初)是一個空對象。

這是它唯一的價值。

因此,當i變為1您試圖在undefined而不是對象上設置屬性。

不要用空對象初始化數組。 需要時將對象添加到數組:

for(var i=0; i<2; i++){
    orders.features[i] = {};

...這意味着在開始之前您不需要數組中的空對象:

orders.features = [];
for(var i=0; i<2; i++){

...但真的沒有必要重復訪問數組的索引並修改對象。

只需創建包含所有數據的對象,然后pushpush送到數組的末尾:

    orders.features = [];
    for(var i=0; i<2; i++){
        const object = {
            geometry: {
                x: "value_here",
                y: "other_value_here"
            }
        };
        orders.features.push(object);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM