简体   繁体   中英

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

I am new to JS, I have been working on this case for 2 days now, experimenting how to get a value from a nested array by index.

This is my original array return from a server:

[
   {
      "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
   }
]

Here's what I have done:

I did var result = JSON.parse(data); then var customer = JSON.parse(JSON.stringify(result[0])); and it gives me this:

在此处输入图像描述

I tried:

var customerdata = [];

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

console.log(customerdata);

but it gives me this:

在此处输入图像描述

I just want something like customer.c_id instead of using loop. is this possible?

Thanks to https://stackoverflow.com/users/9513184/iota and https://stackoverflow.com/users/7941251/superstormer , I solve this by:

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

//result: 4047

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