Reputation: 586
I have the following object consisting of three other objects of type array :
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 ?
Upvotes: 0
Views: 76
Reputation: 964
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);
}
});
Upvotes: 1
Reputation: 5769
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
}
Upvotes: 1
Reputation: 824
You can use Object.keys(brands[brand])
, and, based on your example, you would want Object.keys(brands[brand])[0]
Upvotes: 1