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}]
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}]
Share
Improve this question
asked Dec 2, 2015 at 1:35
random_user_namerandom_user_name
26.2k7 gold badges80 silver badges118 bronze badges
3 Answers
Reset to default 6Would 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 bees:
_.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.
ok, if you must:
var input = {"United States":50, "China":20};
var ouput = _.map(input, function(val, key){ var o = {}; o[key] = val; return o; });
but this is not better than the previous answer. its worse.