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

javascript - Lodash create an object from a collection - Stack Overflow

programmeradmin0浏览0评论

With the following array;

var arr = [
    {"name": "blah"},
    {"version": "v1.0.0"},
    ...
]

I would like to create the following object with lodash;

var obj = {
    "name": "blah",
    "version": "v1.0.0",
    ...
}

P.S. Duplicates don't matter as there won't be any here.

With the following array;

var arr = [
    {"name": "blah"},
    {"version": "v1.0.0"},
    ...
]

I would like to create the following object with lodash;

var obj = {
    "name": "blah",
    "version": "v1.0.0",
    ...
}

P.S. Duplicates don't matter as there won't be any here.

Share Improve this question asked Sep 13, 2016 at 12:39 stackunderflowstackunderflow 1,7146 gold badges25 silver badges40 bronze badges 2
  • 1 Can we see your implementation or what you tried? – Joseph Commented Sep 13, 2016 at 12:40
  • I haven't tried anything, I'm just curious as to what method would be used from lodash or how one might do this? – stackunderflow Commented Sep 13, 2016 at 12:45
Add a ment  | 

3 Answers 3

Reset to default 3

Here is a solution using plain JavaScript.

References:

  1. Object.assign can be used to concatenate Objects({}).
  2. Array.prototype.reduce can be used to minimize the Array([]) values.

var arr = [{
  "name": "blah"
}, {
  "version": "v1.0.0"
}];

var obj = arr.reduce(function(o, v) {
  return Object.assign(o, v);
}, {});

console.log(obj);

Why use lodash when you can do it in pure js?

var arr = [
  {
    "name": "blah"
  }, 
  {
    "version": "v1.0.0"
  }
]

var obj = arr.reduce(function(acc, val) {
  var key = Object.keys(val)[0];
  acc[key] = val[key];
  return acc;
}, {})

console.log(obj)

Lodash implementation.

var arr = [{
  "name": "name"
}, {
  "version": "v1.0.0"
},{
  "manager": "manager"
}];

var result = _.reduce(arr, function(object, value) {
  return _.assign(object, value);
}, {});

console.log(result);
发布评论

评论列表(0)

  1. 暂无评论