首页 > 解决方案 > 循环遍历带有对象的json数组

问题描述

我有一个这种格式的数组:

var items = [{
        "link": {
            "0": "http://www.example.com/"
        },
        "title": {
            "0": "example"
        }
    }, {
        "link": {
            "0": "http://www.example2.com"
        },
        "title": {
            "0": "example2"
        }
    }]

我不知道如何遍历它并在 HTML 中显示它的值。

我使用 jquery 并尝试使用每个循环:

$.each( items, function(i, item) {
        console.log(item); // Uncaught TypeError: Cannot use 'in' operator to search for '6271' in
    })

帮助表示赞赏。谢谢!

编辑:

您的代码在我上面发布的示例中有效。我会尽快接受。但是我注意到,我试图循环的真正 json 并不总是格式正确,这会导致崩溃:

var items = [{
        "link": {
            "0": "http://www.example.com/"
        },
        "title": {
            "0": "example"
        }
    }, {
        "link": {
            "0": "http://www.example2.com"
        },
        "title": {
            "0": "example2: "
            some text here ""
        }
    }]

当循环这个数组时,我得到:

Uncaught SyntaxError: Unexpected identifier

有没有办法跳过所有“损坏”的对象?

标签: javascriptjquery

解决方案


给你一个解决方案

var items = [{
  "link": {
      "0": "http://www.example.com/"
  },
  "title": {
      "0": "example"
  }
}, {
  "link": {
      "0": "http://www.example2.com"
  },
  "title": {
      "0": "example2"
  }
}];

$.each( items, function(i, item) {
  $("body").append(`<span class="title">${item.title["0"]}:</span> <span>${item.link["0"]}</span><br/>`);
});
.title {
  font-weight: bold;
  font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

每个item都是一个对象,用于获取我在解决方案中提供的链接值。


推荐阅读