Abudayah Abudayah - 3 months ago 5
JSON Question

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>

Answer

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]]);
Comments