Skip to content

Instantly share code, notes, and snippets.

@schulace
Created June 19, 2019 16:03
Show Gist options
  • Select an option

  • Save schulace/0929986b659e3fbda90cd29c620b44cb to your computer and use it in GitHub Desktop.

Select an option

Save schulace/0929986b659e3fbda90cd29c620b44cb to your computer and use it in GitHub Desktop.
const retain = (obj, keys) => {
const keepStr = keys.join(', ');
const evalStr = `(() => {const {${keepStr}} = obj;return {${keepStr}};})()`
return eval(evalStr);
}
const obj = {'k1': 'v1', 'k2': 'v2'};
const newObj = retain(obj, ['k2']);
console.log(newObj);
@schulace
Copy link
Copy Markdown
Author

schulace commented Jun 19, 2019

Unfortunately, this is faster than

const retain = (obj, keys) =>
  Object.entries(obj).reduce(
    (acc, [k, v]) => (keys.includes(k) ? { ...acc, [k]: v } : acc),
    {}
  );

However, it is slower than just modifying acc in the reduce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment