简体   繁体   English

用JavaScript分解导入的对象

[英]Destructuring an Imported Object in JavaScript

Let's imagine that I have two files. 假设我有两个文件。 File number one is called obj.js and looks like this: 文件号为obj.js ,看起来像这样:

const obj = {
  item1: 'some text',
  item2: 'some other text',
  item3: 'more text'
  ...
  item99: `yet more text`
}

export default obj

File number 2 looks is called main.js and looks like this: 2号文件的外观称为main.js ,如下所示:

import obj from './obj.js'

Now, here is my question. 现在,这是我的问题。 In file number two ( main.js ) I can access properties off of the obj Object like this: obj.item2 . 在第二个文件( main.js )中,我可以像这样访问obj Object的属性: obj.item2 What I want to know is can I destructure this object so that I can access any of the properties as follows: item2 , item26 , item38 , etc (ie, without the need to preface it with obj. )? 我想知道的是,我可以对这个对象进行解构,以便访问如下所示的任何属性: item2item26item38等(即,不需要以obj. item38 )吗?

If so, any idea how? 如果是这样,有什么想法吗?

I'm not trying to import any particular property, but rather want the option of using whichever properties I chose to without the need to reference obj . 我不是要导入任何特定的属性,而是想要选择使用我选择的任何属性而无需引用obj

You question is simply that how can you destructure all the properties of object. 您的问题很简单,那就是如何分解对象的所有属性。 Actually its dynamic variables names in other words which are not possible. 实际上,它的动态变量名称是不可能的。 But here you want to declare them in global scope its possible using global and dynamic properties names. 但是在这里,您想在全局范围内使用global和动态属性名称声明它们。

import obj from './obj.js'
Object.keys(obj).forEach(x => global[x] = obj[x]);

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

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