Note: ES6 Is welcome, as is loash solutions.
So I have an array, that will only every have two objects of key: value
For example:
[{a: 1}, {b: 2}]
I cannot figure out a solution where it can become: a_1_b_2
as a string.
You cannot assume the key or the value, so you cannot do something like:
let obj = _.merge({}, ...arr);
return `a_${obj.a}_b_${obj.b}`;
Because the key's can be any string and the value can be any number. The object's in the array will only ever have one key and one value and there will only ever be two objects in the array.
With this in mind, how do I create the desired string?
Here's a solution in lodash that uses a combination of lodash#flatMapDeep
and lodash#toPairs
to get an array of keys and values that we can join using lodash#join
.
var array = [{a: 1}, {b: 2}];
var result = _(array).flatMapDeep(_.toPairs).join('_');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>