Last active
April 19, 2022 20:14
-
-
Save tvler/3ed27870e722df4ae914e9608baf0e43 to your computer and use it in GitHub Desktop.
Experimental notation for picking a subset of a js object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getProxy = (target = {}, key) => | |
target[key] || (target[key] = new Proxy({}, { get: getProxy })); | |
const fillPick = (proxy, fn, fromObject = fn(proxy)) => | |
Object.assign( | |
{}, | |
...Object.entries(proxy).map(([key, value]) => ({ | |
[key]: Object.keys(value).length | |
? fillPick(value, fn, fromObject[key]) | |
: fromObject[key], | |
})), | |
); | |
const pick = fn => fillPick(getProxy(), fn); | |
const object = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; | |
const subset = pick(({ a, b, d: { e } }) => object); | |
console.log(subset); // { a: 1, b: 2, d: { e: 4 } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment