0

我想循环json数据但选择产品,困难在于我要选择的对象遵循模式product-*。我想找到一种允许以下内容的代码和平:

$.each(data.products, function(i, product) {
   console.log(product.products_name);
});

实际数据 JSON 是:

{
    "orders_id": "411",
    "customers_name": "Larez",
    "product-1": {
        "product_name": "Walt",
        "product_type": "Poster",
        "product_quantity": "100",
        "product_size": "1/4 Pliego",
        "product_price": "100.00"
    },
    "product-2": {
        "product_name": "Penny",
        "product_type": "Poster",
        "product_quantity": "15",
        "product_size": "1/4 Pliego",
        "product_price": "15.00"
    },
    "product-3": {
        "product_name": "Carol",
        "product_type": "Poster",
        "product_quantity": "50",
        "product_size": "1/4 Pliego",
        "product_price": "50.00"
    },
    "product-4": {
        "product_name": "Julia",
        "product_type": "Poster",
        "product_quantity": "100",
        "product_size": "1/4 Pliego",
        "product_price": "100.00"
    }
}
4

2 回答 2

4

怎么样:

var data = { /* your data */ };
var product,
    i = 1;
while(product = data['product-' + i++]) {
    console.log(product.products_name);
}
于 2013-10-24T16:44:21.377 回答
2

您可以使用 underscore.js 之类的库并执行以下操作来获取产品密钥数组。

r = /product-\d+/
product_keys = _.filter(_.keys(json), function(k) { return r.test(k) });

然后您可以直接使用产品密钥进行迭代

于 2013-10-24T16:52:53.713 回答