简体   繁体   English

自动将 Object 键分布到变量

[英]Automatically Spreading Object Keys to Variables

I've got an object with a series of key/value pairs.我有一个带有一系列键/值对的 object。 I'd like to spread them all out like this:我想像这样将它们全部展开:

const { 
    filterTarget, 
    filter, 
    source, 
    minDate,
    maxDate, 
    skip, 
    limit,
    tracking,
    trackingList,
    sortBy,
    sortOrder
} = req.body;

Is there a faster way for me to do this, so that I don't have to write ALL of the property names, but can rather just spread them out automatically?我有没有更快的方法来做到这一点,这样我就不必写下所有的属性名称,而是可以自动将它们展开? Like:喜欢:

SOMETHING_THAT_ASSIGNS_KEYS_TO_CONSTANTS = req.body;

In the end, I'd need the same result but don't want to write out all the variables if that's not totally necessary.最后,我需要相同的结果,但如果不是完全必要的话,我不想写出所有变量。

You can't do that without assigning the to the window object, something that you should avoid:如果不将 分配给window object,您将无法做到这一点,您应该避免这样做:

 const obj = { filterTarget: "filterTarget value", filter: "filter value", source: "source value" }; Object.entries(obj).forEach(([k, v]) => (window[k] = v)); console.log('filterTarget: ', filterTarget);

However, the reason this is not advisable is because it can backfire.但是,不建议这样做的原因是因为它可能适得其反。 First, if the object you receive ever changes the keys it has, you may get an error:首先,如果您收到的 object 更改了它的密钥,您可能会收到错误消息:

 function applyFilter(obj) { Object.entries(obj).forEach(([k, v]) => (window[k] = v)); //using the expected values console.log( "Applying filter:", filter, "\nsource", source, "\nfilterTarget", filterTarget) } /* time passes and project changes */ //using the function with different values applyFilter({ target: "filterTarget value", //filterTarget was renamed filter: "filter value", source: "source value" });

Second, if your object uses anything that exists in window , the global value would be overwritten and this can lead to errors.其次,如果您的 object 使用window中存在的任何内容,则全局值将被覆盖,这可能会导致错误。 Even worse, you might never notice the error because the functionality might be used by a different piece of code, or even a third-party library.更糟糕的是,您可能永远不会注意到该错误,因为该功能可能被另一段代码甚至第三方库使用。 At worst, this could look like this:在最坏的情况下,这可能看起来像这样:

 function useObject(obj) { Object.entries(obj).forEach(([k, v]) => (window[k] = v)); var c; if (atob) { c = b + a; } else { c = a + b; } return c; } //using the function with different values var result = useObject({ a: "hello", b: "world", atob: false }); console.log("result", result); /* third party code */ var base64Encoded = "REVBREJFRUY="; var decoded = atob(base64Encoded); //error because it was overwritten

The problem is that this could potentially overwrite anything - Array or Date for example, which would break a lot of your code.问题是这可能会覆盖任何东西——例如ArrayDate ,这会破坏你的很多代码。 But it's even more insidious with something like atob which, while not "obscure" does not show up THAT much.但是像atob这样的东西更加阴险,虽然不是“晦涩难懂”,但并没有出现那么多。 However, it could easily be used by third-party code or a completely different part of the application and it would randomly fail.但是,它很容易被第三方代码或应用程序的完全不同部分使用,并且会随机失败。

With this in mind, it is a better idea to move the properties in an object with a shorter name:考虑到这一点,最好使用更短的名称移动 object 中的属性:

 const verylongnameobject = { filterTarget: "filterTarget value", filter: "filter value", source: "source value" }; const obj = {}; Object.entries(verylongnameobject).forEach(([k, v]) => (obj[k] = v)); // OR // const {...obj} = verylongnameobject; console.log('filterTarget: ', obj.filterTarget);

It is not possible to dynamically create constants at scope level, but one can do so at object level using Object.defineProperty() :不可能在 scope 级别动态创建常量,但可以使用Object.defineProperty()在 object 级别这样做:

 'use strict' function createConstants(source) { const result = {}; for (const [key, value] of Object.entries(source)) { Object.defineProperty(result, key, { value: value, enumerable: true, configurable: true, writable: false }); } return result; } const a = createConstants({ filterTarget: 42, filter: 43, source: 44, }); console.log(a); // Throws in 'strict' mode, because members of a are constants a.source = 0;

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

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