Reputation: 1812
I have a javascript function that passes an object that contains multiple other objects, e.g.
createButtons({
normalButtons: {
button: {
type: 'website',
name: 'Website',
}
}
socialButtons: {
socialButton: {
type: 'fb-share',
name: 'Share on Facebook'
},
socialButton: {
type: 'copyUrl',
name: 'Copy Link'
}
}
});
Now i want to iterate through all the socialButtons, but when I do using a for ... in loop, it only seems to get the first item
function createButtons(options) {
for (x in options.socialButtons) {
console.log(options.socialButtons[x]);
}
}
It only logs 1 object, the Facebook one.
Am I doing something wrong or is there a better way to solve this, please let me know.
Thank you!
Upvotes: 1
Views: 58
Reputation: 2776
You are using same property name socialButton
inside socialButtons
object. This is the cause of your problem.
Changing the name name socialButton
to an unique property name will help you achieving what you want.
Upvotes: 0
Reputation: 944556
You are successfully looping over the properties of that object. The problem is that you only have one property.
You defined a value for socialButton
and then you defined another value for socialButton
.
You need to make your property names unique.
Better yet: use an array.
Upvotes: 3
Reputation: 1379
Your object will not gonna work as both of the items in socialButtons: have this same keys, so, the first button will be replaced with second.
I recommend changing second socialButton to socialButton2 and everything should work.
Upvotes: 2