【问题标题】:Unable to iterate through JSON Array using jQuery无法使用 jQuery 遍历 JSON 数组
【发布时间】:2018-06-25 04:10:24
【问题描述】:

我知道这个问题已经被问过很多次了,但是每次我得到未定义的变量时,我都会卡在某个地方来获取数据。有人可以帮助使用 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"
     }
  ]
 }
]

提前致谢。

【问题讨论】:

  • “迭代”是什么意思?你的目标是什么?你想得到什么数据?
  • 我要先获取customer_id

标签: jquery arrays json ajax


【解决方案1】:

如果你想获取 customer_id 的意思,试试data[0].Orderdetails[0].customer_id 其中数据将是 JSON。

【讨论】:

    【解决方案2】:

    您获得的对象是 2 个对象的列表 Orderdetailsproduct 都包含另一个列表。如果你想得到customer_idout of 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
    
    });
    

    【讨论】:

    • 谢谢!!你能告诉我如何使用 for 循环遍历产品 JSON 数组
    • 当然。只需使用forEach()-loop。我编辑了我的答案。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多