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!

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.

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

4 Comments

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?
"If I create an array for each socialButton" — Don't. Create an array containing all the socialButtons.
Yeah sorry, I was being a bit too fast, but that's what I meant
You'd replace for (x in options.socialButtons) { with a standard for (var = 0; etc loop or a call to your_array.forEach.
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.

Comments

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.

Comments

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.