如何在JQuery中执行$ .each

时间:2017-09-02 16:13:20

标签: javascript jquery arrays json cordova

最近几天,我一直试图使用jquery发送所有产品名称的列表。这就是我所拥有的,但它返回undefined或给出它上面的东西。

var ech = data.categories[0];
console.error(str)
$.each(ech, function (idx, obj) {
console.log(obj.packages)
});

这是json文件:

{
  "categories": [
    {
      "id": 920353,
      "order": 0,
      "name": "Packages",
      "only_subcategories": false,
      "subcategories": [],
      "packages": [
        {
          "id": 2410095,
          "order": 0,
          "name": "Account Unban",
          "price": "20.00",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        },
        {
          "id": 2629288,
          "order": 0,
          "name": "Test",
          "price": "0.99",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        }
      ]
    },
    {
      "id": 920903,
      "order": 2,
      "name": "Popular",
      "only_subcategories": false,
      "subcategories": [],
      "packages": [
        {
          "id": 2410111,
          "order": 1,
          "name": "Donate",
          "price": "5.00",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        }
      ]
    }
  ]
}

如何让它显示“帐户取消”和“测试”的产品名称?

2 个答案:

答案 0 :(得分:2)

您实际想要做的是覆盖所有categories(因为它是一个数组)而不是categories数组中第一个项目的所有属性:

var ech = data.categories;
$.each(ech, function (idx, obj) {

检查以下内容:

var data = {
  "categories": [
    {
      "id": 920353,
      "order": 0,
      "name": "Packages",
      "only_subcategories": false,
      "subcategories": [],
      "packages": [
        {
          "id": 2410095,
          "order": 0,
          "name": "Account Unban",
          "price": "20.00",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        },
        {
          "id": 2629288,
          "order": 0,
          "name": "Test",
          "price": "0.99",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        }
      ]
    },
    {
      "id": 920903,
      "order": 2,
      "name": "Popular",
      "only_subcategories": false,
      "subcategories": [],
      "packages": [
        {
          "id": 2410111,
          "order": 1,
          "name": "Donate",
          "price": "5.00",
          "sale": {
            "active": false,
            "discount": "0.00"
          }
        }
      ]
    }
  ]
}
var ech = data.categories;
$.each(ech, function (idx, obj) {
    console.log(obj.packages)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

如果我是正确的,您希望显示每个类别的所有包名称。 如果是这样,你需要第二个(和嵌套的)$ .each,如下所示:

$.each(data.categories, function(idx, obj) {
$.each(obj.packages, function(idx, pack) { console.log(pack.name); });
});

否则,如果您只需要第一个类别的包名称,那么:     $ .each(data.categories [0] .packages,function(idx,pack){console.log(pack.name);});