In JavaScript I am trying to convert an array of objects with similar keys:
[{'a':1,'b':2}, {'a':3,'b':4}, {'a':5,'b':6,'c':7}]
to an object with an array of values for each key:
{'a':[1,3,5], 'b':[2,4,6], 'c':[7]};
using underscore.js 1.4.2.
I have some working code below, but it feels longer and clunkier than just writing nested for loops.
Is there a more elegant way of doing this in underscore? Is there something simple I'm missing?
console.clear();
var input = [{'a':1,'b':2},{'a':3,'b':4},{'a':5,'b':6,'c':7}];
var expected = {'a':[1,3,5], 'b':[2,4,6], 'c':[7]};
// Ok, go
var output = _(input)
.chain()
// Get all object keys
.reduce(function(memo, obj) {
return memo.concat(_.keys(obj));
}, [])
// Get distinct object keys
.uniq()
// Get object key, values
.map(function(key) {
// Combine key value variables to an object
// ([key],[[value,value]]) -> {key: [value,value]}
return _.object(key,[
_(input)
.chain()
// Get this key's values
.pluck(key)
// Filter out undefined
.compact()
.value()
]);
})
// Flatten array of objects to a single object
// [{key1: [value]}, {key2, [values]}] -> {key1: [values], key2: [values]}
.reduce(function(memo, obj) {
return _.extend(memo, obj);
}, {})
.value();
console.log(output);
console.log(expected);
console.log(_.isEqual(output, expected));
Thanks