If my understanding is correct, it appears that the spread syntax would be a suitable solution for your requirements.
The spread syntax "...
" enables you to distribute the key/value pairs from a source object (such as test
) to a target object (like destruct
):
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
const destruct = {
// {a,b}: test <-- invalid syntax
...test // achieves the same using the "spread" syntax
};
console.log(destruct)
Furthermore, if you wish to extract a subset of keys from a source object and include them in a target object, you can accomplish this as follows:
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
/* Spread subset of keys from source object to target object */
const welcomeOnly = {
...({ a, b } = test, { a, b })
}
console.log('exclude goodbye, show welcomes only:', welcomeOnly);
In the second example, we destructure the source object (namely test
) into an object containing only the desired keys (a
and b
).
Within the scope of that expression (between the (
and )
), these keys become accessible as local variables. We capitalize on this capability by passing them to a new object (i.e., { a, b }
). Since the new object is declared after the ,
, it takes precedence as the result of the expression.