Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active April 19, 2022 20:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/3ed27870e722df4ae914e9608baf0e43 to your computer and use it in GitHub Desktop.
Save tvler/3ed27870e722df4ae914e9608baf0e43 to your computer and use it in GitHub Desktop.
Experimental notation for picking a subset of a js object
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