【发布时间】:2021-02-10 13:48:06
【问题描述】:
我有一个对象的对象,类似于这样:
{
file0: {
body: {
prop1: 'abc',
prop2: 123
}
},
file1: {
header: {
prop1: 987,
prop2: 'xyz',
prop3: 0
}
}
}
我想遍历顶层对象(file0、file1 等),然后动态构建以下内容:
window['body'] = { prop1: 'abc', prop2: 123 }
window['header'] = { prop1: 987, prop2: 'xyz', prop3: 0 }
等等等等等等
我使用以下方法完成了这项工作:
export const registerComponents = components => {
for (let component in components) {
window[Object.keys(components[component])[0]] = components[component][Object.keys(components[component])[0]]
}
}
问题:
(1) 这是实现这一目标的最佳方式吗?
(2) 除了for in,还有其他/更好的方法来循环对象吗?
(3) 是否有引用对象属性的简写方式?
【问题讨论】:
-
考虑删除问题 1&2(“什么是最好的......”)?因为它们会导致固执己见的答案。
-
在速度方面最好的对我来说似乎是客观的:D
-
ok.. 查看速度比较
标签: javascript loops object