簡體   English   中英

如何通過 javascript 中的索引從嵌套數組中獲取值?

[英]How to get value from a nested array by index in javascript?

我是 JS 新手,我已經在這個案例上工作了 2 天,試驗如何通過索引從嵌套數組中獲取值。

這是我從服務器返回的原始數組:

[
   {
      "customer":{
         "c_id":"4047",
         "quote_id":"PO3640",
         "post_date":"2021-01-25 06:26:01",
         "first_name":"Brett",
         "last_name":"H",
         "email":"brett@hafs.com.au",
         "phone":"0419778645",
         "postcode":"4128",
         "state_address":null,
         "message":"",
         "computed_price":"4102.00",
         "quote_source":"Piranha Off Road website",
         "follow_up":null,
         "follow_up_date":null
      }
   },
   {
      "vehicle":{
         "v_id":"4220",
         "make":"Toyota",
         "model":"Hilux",
         "year":"2020",
         "cab_type":"Single Cab",
         "engine":"Petrol",
         "vehicle_feature":"Reverse Camera ",
         "fitting_location":"Brisbane, QLD 4014",
         "quote_id":"PO3640"
      }
   },
   {
      "traycanops":{
         "id":"3974",
         "product":"Steel UTE Tray",
         "installation":"Piranha Branch",
         "tray_size":"2400L x 1825W x 260H",
         "tray_color":"Black",
         "tub_removal":"Please remove my tub as part of installation",
         "drivetrain":"2WD",
         "tail_lights":"Standard Globe Light",
         "claim_tub":null,
         "get_tray_floor":null,
         "canopy_size":null,
         "canopy_color":null,
         "paint_color":null,
         "paint_code":null,
         "canopy_type":null,
         "floor_type":null,
         "window_type":null,
         "deck_type":null,
         "doors":null,
         "jack_off_style":null,
         "canopy_finish":null,
         "bundle":"false",
         "powdercoat":"No",
         "powdercoat_ac":null,
         "quote_id":"PO3640",
         "base_price":"$4102.00"
      }
   },
   {
      "accessories":null
   }
]

這是我所做的:

我做了var result = JSON.parse(data); 然后var customer = JSON.parse(JSON.stringify(result[0])); 它給了我這個:

在此處輸入圖像描述

我試過了:

var customerdata = [];

$.each(customer, function(arrkey, arritem) {
  customerdata.push(customerdata[arrkey]=arritem);
});

console.log(customerdata);

但它給了我這個:

在此處輸入圖像描述

我只想要諸如customer.c_id之類的東西,而不是使用循環。 這可能嗎?

感謝https://stackoverflow.com/users/9513184/iotahttps://stackoverflow.com/users/7941251/superstormer解決了這個問題:

var result = JSON.parse(data); 
console.log(result[0].customer.c_id);

//result: 4047

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM