简体   繁体   中英

how to iterate thru json array and pull values with jQuery

So I have the following JSON that is being displayed on an order confirmation page:

var orderDetails = {
    "orderID": "o32770183",
    "orderQty": 3,
    "orderTotal": 575.97,
    "orderShipping": 49.97,
    "orderDiscount": 0,
    "orderTax": 39.74,
    "orderCity": "Norwalk",
    "orderState": "Connecticut",
    "itemId": [
        "sku500134",
        "sku230312",
        "sku133846"
    ],
    "itemQty": [
        1,
        1,
        1
    ],
    "itemPrice": [
        159.99,
        225.99,
        189.99
    ],
    "itemName": [
        "The 'Inaugural' Raymond R Cabernet Sauvignon",
        "H de l'Hospitalet",
        "Chateau Florie Aude"
    ]
}

What would be the best approach to pulling the data out?

Or also, like this - a more dynamic approach - (if you dont know the objects elements)

for(i in orderDetails)
  alert(orderDetails[i])

That's actually not JSON, that's a plain old JavaScript object. You pull the data our just like with any other object

var orderId = orderDetails.orderID;

or

var orderId = orderDetails["orderID"];

or for arrays:

var itemQtyArr = orderDetails.itemQty;
for(var i = 0, max = itemQtyArr.length; i < max; i++){
   console.log("itemQty", i, itemQtyArr[i]);
}

or the dynamic approach Vivek posted (+1 to him)

You can iterate the keys of a Javascript Object using for in

Lets say

a = {"a":"hello","b":"world"};

for(var c in a){
  console.log(c); //will out put a,b in iterations
  console.log(a[c]) //will access values of keys a and b from the object a output hello, world
}

Here is a helpful JSON Editor tool that gives you a visual representation of your JSON object. It lists your named items and gives you the path to access your JSON values: JSON Editor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM