[英]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.