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 ?

6
  • 1
    possible duplicate of Access / process (nested) objects, arrays or JSON Commented Apr 10, 2014 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]. Commented Apr 10, 2014 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 Commented Apr 10, 2014 at 17:46
  • 1
    You should build your data from the beginning so that it looks like {'samsung': [...], 'otherbrand': [...], ...}. Commented Apr 10, 2014 at 17:48
  • 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. Commented Apr 10, 2014 at 18:14

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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
}

1 Comment

But this would only get the first brand name, not all brand names.
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);
    }
});

2 Comments

But this would only get the first brand name, not all brand names.
If you need all brand names then loop over the brands array

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.