简体   繁体   English

解构所有对象属性而不单独命名它们

[英]Destructuring all object properties without naming them individually

Destructuring an object: const p = {...this.props} , I can access any property with p.propertyNameX , p.propertyNameY , etc.. const p = {...this.props}对象: const p = {...this.props} ,我可以使用p.propertyNameXp.propertyNameY等访问任何属性。

I would prefer to simply use propertyNameX and not use p.propertyNameX .我宁愿简单地使用propertyNameX而不是使用p.propertyNameX

Can this be done without having to name all properties of the object like const {propertNameX, propertyNameY, etc...} = {...this.props} ?这是否可以在不必命名对象的所有属性的情况下完成,例如const {propertNameX, propertyNameY, etc...} = {...this.props}

There is not really an option to just copy all your object fields to current scope variables without naming them separately.没有真正的选项可以将所有对象字段复制到当前范围变量而不单独命名它们。

But depending on what you want to achieve there are few other options.但是,根据您想要实现的目标,几乎没有其他选择。

I would strongly recommend you to refractor your code so you won't have to do that, but if it is some short, prototype code you can easily assign all object's properties to global like this:我强烈建议你折射你的代码,这样你就不必这样做了,但如果它是一些简短的原型代码,你可以轻松地将所有对象的属性分配给全局,如下所示:

for ( let prop in p ) {
    global[prop] = p[prop];
}

after that, all of properties can be accesed just like a regular variable, so in your example you can now do之后,所有属性都可以像常规变量一样访问,因此在您的示例中,您现在可以执行

console.log(propertyNameX);

and property (now global variable) value will be displayed in console.和属性(现在是全局变量)值将显示在控制台中。

but keep in mind, this will not set this in your current scope, but as global application values , as side-effect overriding any of previous global variables and making them accessible everywhere.但请记住,这不会在您当前的范围内设置它,而是将其设置为全局应用程序值,作为覆盖任何先前全局变量并使它们在任何地方都可以访问的副作用。 Using global variables is an anty-pattern.使用全局变量是一种反模式。

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

相关问题 解析对象而不指定其属性 - Destructuring an object without specifying its properties 如何仅从DOM Window对象获取属性? (无需单独指定) - How to get the properties from the DOM Window object only? (Without specifying them individually) 使用没有所有键的内部数组解构 object - Destructuring object with inner array without all keys 解构 object 以使所有属性都没有嵌套/单级 - Destructuring an object in order to make the all properties none nested / single level 对象分解为类属性不起作用 - Object destructuring into class properties not working 如何在不命名所有模块的情况下要求从模块中导出多个? - How to require multiple exports from a module without naming all of them? 如何在不在 JavaScript 中单独列出元素的情况下更新元素的许多属性? - How can I update many properties of an element without listing them individually in JavaScript? 扩展对象的属性而不覆盖它们 - Extending object's properties without overwriting them 使用逻辑不是所有元素的对象解构 - Object destructuring with logical NOT all elements 如何在参数的子集上使用 javascript object 解构并保持对单个值中所有剩余属性的引用? - How to use javascript object destructuring on a subset of an argument and maintain reference to all remaining properties in single value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM