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
3 Answers
Reset to default 3Here is a solution using plain JavaScript.
References:
Object.assign
can be used to concatenateObjects({})
.Array.prototype.reduce
can be used to minimize theArray([])
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);