javascript - 为 json 数组中的每个对象创建一个列表

标签 javascript jquery html json

我有一个 json 数组:

[
  {
    "id":"1",
    "0":"1",
    "name":"Quique",
    "1":"Quique"
  },
  {
    "id":"2",
    "0":"2",
    "name":"Kety",
    "1":"Kety"
  }
]

所以,我想从 json 中获取值 id 和 name 并用它们来表示 HTML 中的 json 文件。对我来说完美的结果是这样的:

<div id="container">
  <div>Quique, id 1</div>
  <div>Kety, id 2</div>
</div>

最佳答案

使用Array.prototype.forEach()函数的Javascript解决方案:

var data = [
  {
    "id":"1",
    "0":"1",
    "name":"Quique",
    "1":"Quique"
  },
  {
    "id":"2",
    "0":"2",
    "name":"Kety",
    "1":"Kety"
  }
],
contentStr = "";

data.forEach(function(o){
    contentStr += "<div>"+ o.name +", id "+ o.id +"</div>";
});
document.getElementById('container').innerHTML = contentStr;
<div id="container"> 
</div>

<小时/>

另一种选择是使用 Array.prototype.reduce() 函数:

document.getElementById('container').innerHTML = data.reduce(function(h, o){
  return h + "<div>"+ o.name +", id "+ o.id +"</div>";
}, '');

关于javascript - 为 json 数组中的每个对象创建一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236578/

相关文章:

javascript - 从 javascript 调用 XSLT

javascript - 如何获得表格行中单元格的完整位置(顶部和左侧)?

html - 为什么 DOM 不阻止将 <div> 附加到 <p> 元素中?

c# - MVC3 & JSON.stringify() ModelBinding 返回空模型

javascript - 从父窗口加载内容到子窗口

javascript - polymer 3 : How to implement two way data binding for radio input

javascript - 更改 JQuery 范围 slider 工具提示上的滑动文本

javascript - 父文件准备就绪

javascript - 尝试解构可能长度为 2 的数组时出错

javascript - 在Jquery中获取TD的值