1

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!

asked May 26, 2016 at 10:46
1
  • 1
    You have duplicate keys. socialButton occurs two times Commented May 26, 2016 at 10:49

3 Answers 3

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.

answered May 26, 2016 at 10:49
4
  • 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? Commented May 26, 2016 at 11:18
  • "If I create an array for each socialButton" — Don't. Create an array containing all the socialButtons. Commented May 26, 2016 at 12:33
  • Yeah sorry, I was being a bit too fast, but that's what I meant Commented 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 to your_array.forEach. Commented May 26, 2016 at 12:46
2

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.

answered May 26, 2016 at 10:48
0

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.

answered May 26, 2016 at 11:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.