javascript - 循环遍历带有对象的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
有没有办法跳过所有“损坏”的对象?
解决方案
给你一个解决方案
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
都是一个对象,用于获取我在解决方案中提供的链接值。
推荐阅读
- javascript - 如何从 NodeJs 启动和停止 Electron 应用程序
- google-drive-api - 在 Google Drive API 中使用 createdTime 属性调用 Agument 列表文件 API
- jquery - 无法在 javascript 中访问 Jquery 3.3.1 升级后的隐藏字段值
- vba - 使用另一个范围变量设置范围变量
- ios - 斯威夫特:可解码
- javascript - 反应语义UI按钮悬停
- excel - 保存工作簿的 vba 脚本覆盖输入的文件名
- vuetify.js - v-date-picker 上的默认年份视图
- r-markdown - Rmarkdown 中的 Bibtex - 第二作者的名字和姓氏在引用中交换
- pyomo - 在 Pyomo 中创建 if..then 类型规则(约束)