Searched and searched, can't find this, but I'm assuming it's easy.
I'm looking for the lodash "object" equivalent of lodash _.pairs() - but I want an array of objects (or a collection of objects).
Example:
// Sample Input
{"United States":50, "China":20}
// Desired Output
[{"United States":50}, {"China":20}]
Would something like this be sufficient? It's not lodash, but...
var input = {"United States":50, "China":20};
Object.keys(input).map(function(key) {
var ret = {};
ret[key] = input[key];
return ret;
});
//=> [{"United States":50}, {"China":20}]
Using lodash, this is one way of generating the expected result:
var res = _.map(obj, _.rearg(_.pick, [2,1]));
The above short code snippet can be confusing. Without using the _.rearg
function it becomes:
_.map(obj, function(v, k, a) { return _.pick(a, k); });
Basically the rearg
function was used for reordering the passed arguments to the pick
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With