简体   繁体   中英

How to iterate through all the objects within an object in javascript

I have a javascript function that passes an object that contains multiple other objects, eg

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM