How to convert an object to an array of objects (or a set of objects)

Searched and searched, I can’t find it, but I guess it’s easy.

I am looking for a "lodash" object "equivalent to lodash _. pairs () - but I need an array of objects (or a set of objects).

Example:

// Sample Input
{"United States":50, "China":20}

// Desired Output
[{"United States":50}, {"China":20}]
+4
source share
3 answers

Using lodash, this is one way to get the expected result:

var res = _.map(obj, _.rearg(_.pick, [2,1]));

The above code snippet can be misleading. Without using the function, _.reargit becomes:

_.map(obj, function(v, k, a) { return _.pick(a, k); });

Basically, the function was reargused to reorder the arguments passed to the method pick.

+5

- ? lodash, ...

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

ok, :

var input = {"United States":50, "China":20};
var ouput = _.map(input, function(val, key){ var o = {}; o[key] = val; return o; });

. .

+1
source

Source: https://habr.com/ru/post/1618215/


All Articles