reindexio / youmightnotneedunderscore

https://www.reindex.io/blog/you-might-not-need-underscore/
MIT License
226 stars 18 forks source link

Alternative to _.pick? #14

Closed iansinnott closed 9 years ago

iansinnott commented 9 years ago

Does anyone know of a clever alternative to using _.pick? Usually destructuring keys into their own vars is exactly what you want but sometimes I find myself wanting to destructure keys into an new object, just like _.pick:

const object = { 'user': 'fred', 'age': 40 };

_.pick(object, 'user');
// → { 'user': 'fred' }
pe3 commented 9 years ago

@iansinnott I'm looking for the same thing. Sometimes you want to convert an object to an array. Pick would be handy:

import { pick } from './pick'

let obj = {foo: 'oof', bar: 'rab', baz: 'zab'}

function objectToArray(obj) {
    return Object.keys(obj).map((key) => pick(obj,key))
}
console.log(objectToArray(obj)) 
// [ { foo: 'oof' }, { bar: 'rab' }, { baz: 'zab' } ]
fson commented 9 years ago

I think it's ok to use lodash for things like this where a good native alternative does not exist.

import pick from 'lodash/object/pick';

(If you're building a library, then you could even install it as an individual package so your users don't need to pull in all of lodash: npm install lodash.pick.)

iansinnott commented 9 years ago

OK, thanks. I just wanted to be sure I wasn't missing some cool feature of ES6. I guess lodash.pick will have to do for now

fson commented 9 years ago

@iansinnott Yeah, I don't think there is anything like that.

You could destructure and then make a new object using the object shorthand, but it's not exactly the same thing:

const { user } = object;
const result = { user };
iansinnott commented 9 years ago

Yeah, that's definitiely an alternative. It just doesn't feel as classy as some of the other stuff on this list that really does replace underscore in an elegant way.

On Tue, Oct 6, 2015 at 10:02 AM, Ville Immonen notifications@github.com wrote:

@iansinnott Yeah, I don't think there is anything like that. You could destructure and then make a new object using the object shorthand, but it's not exactly the same thing:

const { user } = object;
const result = { user };

Reply to this email directly or view it on GitHub: https://github.com/reindexio/youmightnotneedunderscore/issues/14#issuecomment-145928494

fson commented 9 years ago

Yeah, agreed :)