使用正则表达式循环Json数据

时间:2013-10-24 16:37:38

标签: javascript jquery regex json

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

$.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"
    }
}

2 个答案:

答案 0 :(得分:4)

怎么样:

var data = { /* your data */ };
var product,
    i = 1;
while(product = data['product-' + i++]) {
    console.log(product.products_name);
}

答案 1 :(得分:2)

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

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

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