[英]Loop through json array with objects
I´ve got an array in this format: 我有一个这种格式的数组:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2"
}
}]
I can´t figure out how to loop through it and display its values in HTML. 我不知道如何遍历它并以HTML显示其值。
Im using jquery and have tried using an each-loop: 我正在使用jQuery,并尝试使用每个循环:
$.each( items, function(i, item) {
console.log(item); // Uncaught TypeError: Cannot use 'in' operator to search for '6271' in
})
Help appreciated. 帮助表示赞赏。 Thanks!
谢谢!
EDIT: 编辑:
Your code works in the example i posted above. 您的代码在我上面发布的示例中有效。 I will accept asasp.
我会接受asasp的。 I noticed however that the real json im trying to loop is not always properly formatted which leads to a crash:
但是我注意到,尝试循环的真实json并非总是正确格式化,从而导致崩溃:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2: "
some text here ""
}
}]
When looping this array i get: 循环此数组时,我得到:
Uncaught SyntaxError: Unexpected identifier
Is there a way to maybe skip all "broken" objects? 有没有办法跳过所有“破碎”的物体?
Fast and dirty: 快速又肮脏:
for (item of items) {
console.log(item.link[0])
console.log(item.title[0])
}
Here you go with a solution 在这里你有一个解决方案
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>
Each item
is an object, to get the link value I've provided in the solution. 每个
item
都是一个对象,用于获取我在解决方案中提供的链接值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.