user1272965 user1272965 - 7 months ago 12
Javascript Question

Turn an object into an array of single-key objects (with underscore?)

I have an object like this:

var o = { foo:"foo", bar:"bar" }


I'd like an output like this:
[ { foo:"foo" }, { bar:"bar" } ]


I'd like the code to be concise, and usually underscore provides that. I've gotten this far...

_.map(_.pairs(o), function(pair) { return { pair[0] : pair[1] }; });


But of course I can't use an evaluated expression as the key in that code. I think I can do this...

_.map(_.pairs(o), function(pair) {
var kv = {};
kv[pair[0]] = pair[1];
return kv;
});


But I was hoping to be concise. And that ain't. Seems like there's a simple one-liner out there that I'm too dumb to see. Is there?

PS - I want this because I want to turn the object into a mongo query disjunction, like this:

{ $or: [ { foo:"foo" }, { bar:"bar" } ] }

Answer

Your oneliner works in ES6 if you change pair[0] to [pair[0]]:

_.map( _.pairs( o ), pair => ( { [pair[0]] : pair[1] } ) );

You can also do it in ES6 without using underscore like this:

Object.keys( o ).map( key => ( { [key]: o[key] } ) );

JSFiddle

Or slightly shorter with underscore:

_.keys( o ).map( key => ( { [key]: o[key] } ) );

or:

_.map( o, (value, key) => ( { [key]: value } ) ) );