I've got an object with a series of key/value pairs. 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 :
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 :
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. 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. But it's even more insidious with something like atob
which, while not "obscure" does not show up THAT much. 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 :
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);