简体   繁体   中英

Access first array in javascript object

I'm trying to access the first array of javascript object

Date:

      var data = {};
      data['bmw'] = {
        'google':[
          'seller1',
          'seller2',
          'seller3',
        ],
        'microsoft':[
          'seller3',
          'seller4',
          'seller5',
        ],
      };

Output should be:

array(
              'seller1',
              'seller2',
              'seller3',
)

my code (not working)

<script>
    data[Object.keys(data)[0]]; // return Object {item_type1: Array[3], item_type2: Array[3]}

    data[Object.keys(data)[0]][0]; // return undefined
</script>

How can you have two keys with the same name. Its obvious that that the last one will override the first key and you will be able to access the data of the last key. In order to get the data from the first key change the name and then run data[Object.keys(data)[0]] and pass key and value to it. For key 0 you will get the first object and then you can loop inside it to get the values. Updated the answer. Check this.

 var data = {};
  data['bmw'] = {
    'google':[
      'seller1',
      'seller2',
      'seller3',
    ],
    'microsoft':[
      'seller3',
      'seller4',
      'seller5',
    ],
  };

 var first = data[Object.keys(data)[0]]; 

 console.log(first[Object.keys(first)[0]]);

Try:

data['dynamic_name']

You'll need to access the properties by 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