2017-02-27 10 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のすべてを取得していないのですか?

第2に、私はどのようにすべてを得るべきですかoccurrence

そして最後に、私は、このような{"image": "cat.jpg"}としてeventsに新しいキー/値のペアを追加することができますどのようになるように、このような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); 
 
}

関連する問題