0

I want to loop on json data but selecting products, the difficulty lies in that the objects that I want to select follow a pattern product-*. I want to find a sort peace of code that allows something like below:

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

The actual data JSON is:

{
    "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"
    }
}
1
  • Do you have the ability to change the data you receive? It would be much more straightforward to handle a list of products for the order rather than generic product-1, product-2, etc. Though I obviously don't know the specifics of your data. Commented Oct 24, 2013 at 16:43

2 Answers 2

4

How about:

var data = { /* your data */ };
var product,
    i = 1;
while(product = data['product-' + i++]) {
    console.log(product.products_name);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps you should increment i =P
Works for the above example, but would break if product-i is not consecutive (not criticizing the answer, just pointing out what could go wrong).
Thanks Mike, love you solution since it works without any libraries and to Steve point in this case the server makes incremental changes
2

You could use library like underscore.js and do something like the following to get an array of the product keys.

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

Which you can then iterate through directly with just the product keys

2 Comments

Good idea. You should probably declare the regex outside the _.filter() though so you only create one instance of it instead of N.
agreed, this was just a quick example but you get the idea. i'll update the example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.