You cannot do this. By the very name of the resource - de-structuring -, you are removing, unstructured an object. There is no way to use a "disruptor" as a tool to build other objects.
What you can do is create a function that does that for you, as a pick
:
function pick(obj, props) {
const newObj = {};
for (const prop of props) newObj[prop] = obj[prop];
return newObj;
}
const obj = { a: 1, b: 2, c: 3 };
console.log(pick(obj, ['a', 'c']));
It would be very interesting to have a language syntax to solve these points that are important to maintain the quality of a code and facilitate maintenance.
In this case, use Typescript or some other language. Javascript will not always guarantee you this type of security.
However, in case you are using Typescript, you can create something a little more complex that will give you the Intellisense of some editors such as Vscode:
function pick<Obj extends { [key: string]: unknown }, Props extends keyof Obj>(
obj: Obj,
props: Array<Props>
): { [key in Props]: Obj[key] } {
const newObj: Pick<Obj, Props> = {} as Pick<Obj, Props>;
for (const prop of props) newObj[prop] = obj[prop];
return newObj;
}
const obj = { a: 1, b: 2, c: 3 };
const result = pick(obj, ['a', 'c']);
console.log(result);
See working on Typescript playground.
Or you can use libraries that already exist, like the function pick
, of the Lodash, which also offers this Intellisense if you are using Typescript.
Reversed, the scope of the question cannot be modified after answers are presented. Create a New Question with another scope.
– Augusto Vasques