Traverse json data using jquery

◇◆丶佛笑我妖孽 提交于 2019-12-01 08:12:51

问题


I have following json data

[
  {
    id: "79",
    title: "Web+Infographics",
    path: "web-infographics"
  },
  {
    id: "80",
    title: "Miscellaneous",
    path: "miscellaneous"
  },
  {
    id: "81",
    title: "Entertainment",
    path: "entertainment"
  }
]

and i want to get the id, title and path out of it using jquery how can i do that? Thanks in advance.


回答1:


Quite simple, use jQuery.each:

$.each(data, function (index, item) {
  console.log(item);
});

But, you don't really need jQuery for this simple task, give the native Array.prototype.forEach a try:

data.forEach(function (item) {
  console.log(item);
});

If you have to support older browsers and don't want to depend on a library, a for-loop could to the trick:

for (var i = 0; i < data.length; ++i) {
  var item = data[i];
}



回答2:


<script>

var data = [
  {
    id: "79",
    title: "Web+Infographics",
    path: "web-infographics"
  },
  {
    id: "80",
    title: "Miscellaneous",
    path: "miscellaneous"
  },
  {
    id: "81",
    title: "Entertainment",
    path: "entertainment"
  }
];

$.each(data, function(key, value) {
    alert(value.id + ", " + value.title + ", " + value.path);
});

</script>


来源:https://stackoverflow.com/questions/17947796/traverse-json-data-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!