I have this situation where I want to use the same variable name multiple times with object desctructuring:
let {body, response} = await requestp('get', `${cdtAPIUrl}/whitelist`, headers);
let parsedBody = await siamese.parse(body);
assert(parsedBody.success, 'response body should have a success property.');
assert(parsedBody.success.length === usernames.length, 'wrong number of items in response body array.');
let {body, response} = await requestp('get', `${cdtAPIUrl}/caches/whitelist`, headers);
let parsedBody = await siamese.parse(body);
but when I run the script with node, node will complain before runtime:
SyntaxError: Identifier 'body' has already been declared
there are two problems which prevent me from getting an easy solution:
I can't do this with object destructuring:
let {a,b} = c;
{a,b} = c; // not allowed
I can't rename body or response, because this is what is returned by the call.
What should I do?
Maybe the best thing to do is something like:
let {body,response} = ...
let {body:body1, response:resp1} = ...
I can't do this with object destructuring:
{a,b} = c;
You can, you just need to put it in parenthesis to be syntactically valid:
({a, b} = c);
Maybe the best thing to do is something like
let {body:body2, response:resp2} = …
Yes, that's the best solution indeed. You might even want to use const instead of let.
What should I do?
Another solution, which I wouldn't necessarily recommend but just want to mention for completeness, is to introduce separate scopes for the variables:
{
let {body, response} = await requestp('get', `${cdtAPIUrl}/whitelist`, headers);
let parsedBody = await siamese.parse(body);
assert(parsedBody.success, 'response body should have a success property.');
assert(parsedBody.success.length === usernames.length, 'wrong number of items in response body array.');
}
{
let {body, response} = await requestp('get', `${cdtAPIUrl}/caches/whitelist`, headers);
let parsedBody = await siamese.parse(body);
}
And of course you can also just use var instead of let, which doesn't bitch about redeclarations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With