【问题标题】:Shorthand for looping through an object of objects循环遍历对象对象的简写
【发布时间】:2021-02-10 13:48:06
【问题描述】:

我有一个对象的对象,类似于这样:

{
  file0: {
    body: {
      prop1: 'abc',
      prop2: 123
    }
  },
  file1: {
    header: {
      prop1: 987,
      prop2: 'xyz',
      prop3: 0
    }
  }
}

我想遍历顶层对象(file0file1 等),然后动态构建以下内容:

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


【解决方案1】:

您可以将嵌套对象分配给window,而无需迭代对象。

const
    object = { file0: { body: { prop1: 'abc', prop2: 123 } }, file1: { header: { prop1: 987, prop2: 'xyz', prop3: 0 } } };

Object.values(object).forEach(o => Object.assign(window, o));

console.log(body);
console.log(header);

【讨论】:

  • oo,我放了我要放的代码,它与我们的近战>:D
【解决方案2】:

我将只显示选项之间的速度差异。
享受:D

//your code
const registerComponents = components => {
  for (let component in components) {
    window[Object.keys(components[component])[0]] = components[component][Object.keys(components[component])[0]]
  }
}

//100k dude code
const hisCode=(components)=>{
  Object.values(components).forEach(o => Object.assign(window, o));
}

//just for fun, my code >:D
const myCode=(components)=>{
  const x=Object.keys(components)
  for(let i=0;i<x.length;i++){
    Object.assign(window,components[x[i]])
  }
}

//speed tester
function speedTest(fn,a){
  var t1=new Date()
  for(var i=0;i<999999;i++){fn(a)}
  return new Date()-t1
}

console.log(`your code's speed is ${speedTest(registerComponents,object)} ms\n100k dude code's speed is ${speedTest(hisCode,object)} ms\nJust for fun, my code's speed is ${speedTest(myCode,object)} ms`)
<script>
window.object = {
  file0: {
    body: {
      prop1: 'abc',
      prop2: 123
    }
  },
  file1: {
    header: {
      prop1: 987,
      prop2: 'xyz',
      prop3: 0
    }
  }
};
</script>

【讨论】:

    【解决方案3】:

    简单干净的代码。

    const obj={ //example object
      file0: {
        body: {
          prop1: 'abc',
          prop2: 123
        }
      },
      file1: {
        header: {
          prop1: 987,
          prop2: 'xyz',
          prop3: 0
        }
      }
    }
    
    Object.keys(obj).forEach((topLevelKey) => {
          const nestedObject = Object.keys(obj[topLevelKey])[0];// 'body', 'header', etc
          window[nestedObject] = obj[topLevelKey][nestedObject];
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2014-02-22
      • 2020-12-06
      • 1970-01-01
      • 2020-04-30
      • 2017-06-12
      • 2015-10-31
      • 2014-11-30
      相关资源
      最近更新 更多