0

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>
6
  • 1
    There are no guaranty of order inside objects. Commented Aug 17, 2016 at 9:30
  • 2
    You can't have two objects under the same key. You'll only have one 'dynamic_name' array in data object and it will be the second one. Commented Aug 17, 2016 at 9:31
  • @jcubic – Can object have multiple key having identical name ? Commented Aug 17, 2016 at 9:32
  • If you preparing this response from SERVER then add it to one single key with values as array of array or array like object. your property will overwritten with last element.So u will not get array Commented Aug 17, 2016 at 9:34
  • @Maggie I update it now, is it right or wrong ? Commented Aug 17, 2016 at 9:44

2 Answers 2

2

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]]);
Sign up to request clarification or add additional context in comments.

1 Comment

awesome awesome :)
-1

Try:

data['dynamic_name']

You'll need to access the properties by name.

2 Comments

data is concated with second array element
the name is dynamic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.