无法使用jQuery遍历JSON数组

时间:2018-06-25 04:10:25

标签: jquery arrays json ajax

我知道这个问题已经被问过很多次了,但是每次遇到未定义的变量时,我都会停留在某个地方以获取数据。有人可以帮助使用jquery ajax遍历JSON数据吗?

[  
 {  
  "Orderdetails":[  
     {  
        "errorMsg":"success",
        "customername":"Walk In Customer",
        "grandtotal":"1496.00",
        "outletname":"Pradhan Ji Mobile",
        "paymentmethodname":"Cash",
        "customer_id":"1",
        "outlet_id":"13"
     }
  ]
},
{  
  "product":[  
     {  
        "product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
        "product_code":"5674664",
        "price":"374.00",
        "qty":"2"
     },
     {  
        "product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
        "product_code":"5674665",
        "price":"374.00",
        "qty":"1"
     },
     {  
        "product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
        "product_code":"5674666",
        "price":"374.00",
        "qty":"1"
     }
  ]
 }
]

提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果您想获取customer_id的意思,请尝试data[0].Orderdetails[0].customer_id 数据将为JSON。

答案 1 :(得分:1)

您获得的对象是2个对象Orderdetailsproduct的列表,它们都包含另一个列表。如果要从customer_id中提取Orderdetails,可以按以下步骤进行。

// let's assume the list is called jsonList.

// Orderdetails is an element of the first list
const orderdetails = jsonList[0].Orderdetails;

// Then get the customer_id out of the first list in Orderdetails
const customer_id = Orderdetails[0].customer_id;

或者以较短的方式完成所有这些操作

const customer_id = jsonList[0].Orderdetails[0].customer_id;
  

编辑

如果要遍历product,请使用.forEach()

// get the list product
const product = jsonList[0].product;

// iterate through it with forEach()
product.forEach( element => {

    // you now have access to the fields of each single element of the list
    console.log('product_name', element.product_name);
    console.log('product_code', element.product_code);

    // .. and so on

});