简体   繁体   English

如何遍历javascript对象中的所有对象

[英]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 我有一个javascript函数,该函数传递包含多个其他对象的对象,例如

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 现在我想遍历所有的socialButtons,但是当我确实使用for ... in循环时,它似乎只能得到第一项

function createButtons(options) {
    for (x in options.socialButtons) {
        console.log(options.socialButtons[x]);
    }
}

It only logs 1 object, the Facebook one. 它仅记录1个对象,Facebook 1个。

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 . 您定义的值socialButton ,然后你定义的另一个值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. 您的对象将不会像socialButtons中的两个项目一样起作用:具有相同的键,因此,第一个按钮将被替换为第二个按钮。

I recommend changing second socialButton to socialButton2 and everything should work. 我建议将第二个socialButton更改为socialButton2,然后一切正常。

You are using same property name socialButton inside socialButtons object. 您正在socialButtons对象中使用相同的属性名称socialButton 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更改为唯一的属性名称将有助于您实现所需的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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