簡體   English   中英

使用for循環迭代對象和數組,並添加鍵/值對

[英]Iterate object and array with for loop and add key/value pair

我正在嘗試了解如何遍歷類似於以下內容的對象:

var json = {"tsn": {
    "events": [
        {
          "title": "Lorem ipsum",  
          "description": "Dolor sit"
        },
        {
          "title": "Duis aute irure",  
          "description": "eu fugiat nulla pariatur"
        },
      ],
    "occurrence": [
        "Music",
        "Party"
      ]
    }    
};

我想按照下面的代碼顯式地使用for循環(而不是for in

for(var i = 0; i < json.length; i++) {
    console.log(json.tsn.events[i].title);
}

為什么上面的代碼沒有得到全部title

其次,我應該如何得到所有occurrence

最后,我如何向events添加新的鍵/值對,例如{"image": "cat.jpg"}以便json對象的結果如下:

var json = {"tsn": {
    "events": [
        {
          "title": "Lorem ipsum",  
          "description": "Dolor sit",
          "image": "cat.jpg"
        },
        {
          "title": "Duis aute irure",  
          "description": "eu fugiat nulla pariatur",
          "image": "dog.jpg"
        },
      ],
    "occurrence": [
        "Music",
        "Party"
      ]
    }    
};

因為您使用的長度錯誤。 采用:

for (var i=0;i<json.tsn.events.length; i++) { ...

然后你應該是金。 對於這種情況,它與-循環大致相同:

for (var i=0;i<json.tsn.occurrence.length; i++) {
    console.log(json.tsn.occurrence[i]);
}

而且您還將這些值拉回去。

json.tsn.events是一個數組。

json.tsn.events有一個長度。

json.tsn.events[i]試圖使用迭代器遍歷數組。

json.length嘗試使用頂級對象而不是數組來計算迭代器。

您需要使用數組的長度。 json.tsn.events.length

如果可以使用of關鍵字,則可以執行此操作,該操作與運行for循環基本相同,但較為冗長,但無法訪問索引。

 var json = {"tsn": { "events": [ { "title": "Lorem ipsum", "description": "Dolor sit" }, { "title": "Duis aute irure", "description": "eu fugiat nulla pariatur" }, ], "occurrence": [ "Music", "Party" ] } }; for (let event of json.tsn.events) { console.log(event.title); } for (let occur of json.tsn.occurrence) { console.log(occur); } 

我個人寧願使用forEach進行此類操作。 我會這樣做:

var json = {"tsn": {
"events": [
    {
      "title": "Lorem ipsum",  
      "description": "Dolor sit"
    },
    {
      "title": "Duis aute irure",  
      "description": "eu fugiat nulla pariatur"
    },
  ],
"occurrence": [
    "Music",
    "Party"
  ]
}    
};

var events = json.tsn.events;

// loop to iterate through array of tsn events
events.forEach(function(item){
    console.log(item.title); // to print each of the titles
    item["image"] = "yourImage.jpg"; // will add to each item the image
    // ... do any other item specific operation
});

要遍歷事件,我將在不同的forEach中執行相同的操作,因為它們的長度都不同。

暫無
暫無

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

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