通过格式不佳的对象进行迭代

时间:2014-02-12 14:18:03

标签: javascript

我有一个非常糟糕的javascript对象:

commits = {
  commit: {
    name: 'First commit'
  },
  commit: {
    name: 'Second commit'
  }
}

正如您所看到的,commits对象的每个子对象都被称为commit,所以它实际上排除了使用for ... in ...或任何其他javascript循环的选项(好吧,这就是我的意思)想想,但我是一个非常糟糕的JS程序员,所以我可能错了)。所以,问题是,我如何遍历该对象?

请记住我不能在这里使用jQuery 我无法重写该对象


编辑:从以下json中解析该对象:

{
  "commits": {
    "commit": {
      "name": "First commit"
    },
    "commit": {
      "name": "Second commit"
    },
  }
}

1 个答案:

答案 0 :(得分:0)

考虑到您提供的github link中发布的JSON,您不需要做很多事情。

JSON字符串似乎是有效的,除了它在字符串末尾缺少}。修复后,它解析得很好:

JSON.parse('{\n  \"accountURL\": \"https://domain.com\",\n  \"newCommitsCount\": \"1\",\n  \"pushURL\":\"https://domain.com/project/64249/git/source/compare/revisions/0b6438955f2a5a7981fd25cfa5b48fe3fb4c888d,7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n  \"unsubscribeURL\": \"https://domain.com:443/unsubscribe?token=receiverToken&type=COMMITS&projectId=64249\",\n  \"invokerEmail\": \"email@email.com\",\n  \"projectURL\": \"https://domain.com/project/64249\",\n  \"projectId\": \"64249\",\n  \"afterPushRevision\": \"7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n  \"invokerId\": \"38074\",\n  \"pushDate\": \"2014-02-11T15:26:36+0000\",\n  \"beforePushRevision\": \"0b6438955f2a5a7981fd25cfa5b48fe3fb4c888d\",\n  \"repositoryURL\": \"git_url\",\n  \"subdomain\": \"subdomain\",\n  \"domain\": \"domain\",\n  \"branch\": \"develop\",\n  \"invokerProfileURL\": \"url\",\n  \"commitsCount\": \"1\",\n  \"invokerSmallAvatarURL\": \"xx\",\n  \"projectName\": \"NAME\",\n  \"invoker\": \"Invoker Name.\",\n  \"commits\": {\"commit\":   {\n    \"revision\": \"7771e638d1356a14d1dc46f3f5cfaab858370a5e\",\n    \"commitMessage\": \"quickfix\",\n    \"committerId\": \"38074\",\n    \"committerEmail\": \"email\",\n    \"committerName\": \"Name.\",\n    \"commitDate\": \"2014-02-11T15:26:27+0000\",\n    \"commitURL\": \"https://domain.com/project/64249/git/source/commit/develop/7771e638d1356a14d1dc46f3f5cfaab858370a5e\"  }}}')