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!
3 Answers 3
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.
-
If I create an array for each socialButton, what would that change regarding iterating through the array and getting for instance the 'type' of each socialButton?Mats Raemen– Mats Raemen2016年05月26日 11:18:15 +00:00Commented May 26, 2016 at 11:18
-
"If I create an array for each socialButton" — Don't. Create an array containing all the socialButtons.Quentin– Quentin2016年05月26日 12:33:27 +00:00Commented May 26, 2016 at 12:33
-
Yeah sorry, I was being a bit too fast, but that's what I meantMats Raemen– Mats Raemen2016年05月26日 12:45:28 +00:00Commented May 26, 2016 at 12:45
-
You'd replace
for (x in options.socialButtons) {
with a standard for (var = 0; etc loop or a call toyour_array.forEach
.Quentin– Quentin2016年05月26日 12:46:32 +00:00Commented May 26, 2016 at 12:46
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.
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.
socialButton
occurs two times