最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to convert object into array of objects (or collection of objects) - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

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 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.

发布评论

评论列表(0)

  1. 暂无评论