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.

2
  • 1
    Can we see your implementation or what you tried? 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? Commented Sep 13, 2016 at 12:45

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thank you, I just like lodash for its cleanliness.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.