random_user_name
random_user_name

Reputation: 26160

how to convert object into array of objects (or collection of objects)

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}]

Upvotes: 4

Views: 2044

Answers (3)

Ram
Ram

Reputation: 144679

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.

Upvotes: 5

Hunan Rostomyan
Hunan Rostomyan

Reputation: 2176

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}]

Upvotes: 6

mkoryak
mkoryak

Reputation: 57928

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.

Upvotes: 1

Related Questions