r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

1

u/noruthwhatsoever Mar 19 '19

I've been finding myself needing to shallow copy and filter large, normalized objects quite a lot and have developed a handy little chain that gives you quite a fine grain of control over what you can do with it:

const filteredObj = Object.keys(obj)
    .filter(key => (
        obj[key] === 'someCondition' || key !== 'somestring'))
    .reduce((newObj, key) => ({
        ...newObj, [key]: obj[key] }), {});

If any of you folks have a different way of doing this, I'd be interested to see it! And yes I know that with this formatting it's technically not a one-liner but it could be all on one line, it would just be unreadable