简体   繁体   中英

How to call array from javascript?

I want to call array but still failed. Here is my JS

var dataLayer =
[
    {
        "id" : "993932",
        "name" : "Foo Bar",
        "total_price" : "867252",
        "Recommended" : 
        [
            {
                "hotel_name" : "Four Season",
                "tripadvisor_ratings" : "5.0"
            },
            {
                 "hotel_name" : "Amaris Hotel",
                 "tripadvisor_ratings" : "5.0"
            }
        ];

var a = "<div>"+ dataLayer.hotel_name +"</div>"

or you can check in https://jsfiddle.net/dedi_wibisono17/7fnzofg1/1/

The result is undefined . Anyone to help me? Thank you

Here datalayer is an array of object and the key Recommended is also an array of object so to access them you need to first select the element in the index.

dataLayer[0] will fetch the first object in your array which is the only one in your case

{
        "id" : "993932",
        "name" : "Foo Bar",
        "total_price" : "867252",
        "Recommended" : [
         {
            "hotel_name" : "Four Season",
            "tripadvisor_ratings" : "5.0"
         },
         {
             "hotel_name" : "Amaris Hotel",
             "tripadvisor_ratings" : "5.0"
         }
         ]
    }

then the key Recommended also has an array of object

[
     {
        "hotel_name" : "Four Season",
        "tripadvisor_ratings" : "5.0"
     },
     {
         "hotel_name" : "Amaris Hotel",
         "tripadvisor_ratings" : "5.0"
     }
 ]

so, you need to access them using index.

dataLayer[0].Recommended[0] will select the first object

{
     "hotel_name" : "Four Season",
     "tripadvisor_ratings" : "5.0"
}

dataLayer[0].Recommended[0].hotel_name to select the key hotel_name

To iterate over all the objects in recommended key array you can use forEach

 dataLayer[0].Recommended.forEach(function(obj){
    console.log(obj.hotel_name);
  }); 

 var dataLayer = [ { "id" : "993932", "name" : "Foo Bar", "total_price" : "867252", "Recommended" : [ { "hotel_name" : "Four Season", "tripadvisor_ratings" : "5.0" }, { "hotel_name" : "Amaris Hotel", "tripadvisor_ratings" : "5.0" } ] } ]; dataLayer[0].Recommended.forEach(function(obj){ console.log(obj.hotel_name); }); 

  var dataLayer = [ { "id" : "993932", "name" : "Foo Bar", "total_price" : "867252", "Recommended" : [ { "hotel_name" : "Four Season", "tripadvisor_ratings" : "5.0" }, { "hotel_name" : "Amaris Hotel", "tripadvisor_ratings" : "5.0" } ] } ]; alert(dataLayer[0].Recommended[0].hotel_name); alert(dataLayer[0].Recommended[1].hotel_name); 

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