使用for循环迭代对象和数组并添加键/值对

时间:2017-02-27 22:30:30

标签: javascript

我正在尝试了解如何迭代类似于以下内容的对象:

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

4 个答案:

答案 0 :(得分: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 :(得分:1)

json.tsn.events是一个数组。

json.tsn.events有一个长度。

json.tsn.events[i]正在尝试使用迭代器遍历数组。

json.length正在尝试使用顶级对象而不是数组来计算迭代器。

您需要使用数组的长度。 json.tsn.events.length

答案 2 :(得分:1)

如果您可以使用of关键字,则可以执行此操作,这与运行for循环基本相同,但不太详细但无法访问索引。

&#13;
&#13;
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);
}
&#13;
&#13;
&#13;

答案 3 :(得分: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中做同样的事情,因为它们都有不同的长度。