2017-02-27 78 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); 
 
}