2017-02-27 46 views
1

我想了解如何遍歷類似於以下對象:迭代對象,並使用for循環數組,並添加鍵/值對

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" 
     ] 
    }  
}; 
+0

一個常規的'for'循環用於數組 - 你有一個對象,你的對象中的一個鍵包含一個數組,因此迭代該鍵。 'for(var i = 0; i tymeJV

+0

JSON是一種字符串格式。你有一個對象。除了變量的名稱之外,我已經在您的問題中刪除了對JSON的引用。 –

回答

1

個人而言,我寧願使用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,因爲它們都具有不同的長度。

2

因爲你使用了錯誤的長度。使用:

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

而且您還將這些值拉回。

1

json.tsn.events是一個數組。

json.tsn.events有長度。

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

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

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

1

如果你可以使用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) 
 
{ 
 
\t console.log(event.title); 
 
} 
 

 
for (let occur of json.tsn.occurrence) 
 
{ 
 
\t console.log(occur); 
 
}

相關問題