Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}]
like image 895
random_user_name Avatar asked Dec 14 '22 10:12

random_user_name


2 Answers

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}]
like image 143
Hunan Rostomyan Avatar answered Dec 17 '22 01:12

Hunan Rostomyan


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.

like image 24
undefined Avatar answered Dec 17 '22 00:12

undefined