0

I have the following object consisting of three other objects of type array :

enter image description here

I want to get the text samsung out of that object and the rest of the objects. I have tried using a for in loop but I am getting the keys 0, 1 , 2.

for(brand in brands){
 console.log(brand)  // prints out `0, 1 , 2`
} 

so I added another nested for in loop, but than I get 0, 0, 0 which are the keys within samsung, and other array objects within the rest of the objects.

What am i missing ?

LogixMaster
  • 586
  • 2
  • 11
  • 36
  • 1
    possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Apr 10 '14 at 17:38
  • 2
    `brands` is an array of objects, each object having one property. I would suggest to convert the data to a single object with multiple properties, then your code would work. If you can't, then you are looking for `Object.keys(brands[brand])[0]`. – Felix Kling Apr 10 '14 at 17:39
  • @FelixKling thanks for your insightful comment. would you be kind enough to share/elaborate more on how I can convert it to single object ? thanks a heaps – LogixMaster Apr 10 '14 at 17:46
  • 1
    You should build your data from the beginning so that it looks like `{'samsung': [...], 'otherbrand': [...], ...}`. – Felix Kling Apr 10 '14 at 17:48
  • Ah! you mean rebuild.. in that case I can't, but will definitely keep this in mind! thanks – LogixMaster Apr 10 '14 at 18:12
  • 1
    You can also convert the data structure, but that only makes sense if you are going to do more things than just list the brand names. – Felix Kling Apr 10 '14 at 18:14

3 Answers3

1

You can use Object.keys(brands[brand]), and, based on your example, you would want Object.keys(brands[brand])[0]

Charlie G
  • 814
  • 9
  • 22
1

Your loop is looping through the entire array, rather than the keys of an object.

var brand = brands[0];
for ( var i in brand )
  console.log( brand[i] ) // -> samsung

Or to get them all:

for ( var i = 0; i < brands.length; i++){
    var brand = brands[i];
    for ( var i in brand )
      console.log( brand[i] ) // -> samsung
}
ncksllvn
  • 5,699
  • 2
  • 21
  • 28
1

You can try

for(brand in brands[0]){
  console.log(brand);
} 

assuming the name of the array to be brands

EDIT

For all the elements in the array brands

brands.forEach(function(v){
    for(brand in v){
      console.log(brand);
    }
});
Abhishek Prakash
  • 964
  • 2
  • 10
  • 24