配列内のオブジェクトのキーで集計する
by bc_rikko
HTML
<h2>lodash</h2>
<pre id="lodash"></pre>
<h2>es6</h2>
<pre id="es6"></pre>
<h2>es5</h2>
<pre id="es5"></pre>
JavaScript
const target = [
{
name: 'taro',
age: 10
},
{
name: 'jiro',
age: 20,
email: '[email protected]'
},
{
name: 'saburo',
age: 30,
email: '[email protected]'
}
]
/* WANT!!
{
'name': ['taro', 'jiro', 'saburo'],
'age': [10, 20, 30]
}
*/
// lodash 2.2.1
const tallyTarget1 = target => {
const keys = _.uniq(_.flatten(target.map(t => Object.keys(t))))
const result = {}
keys.forEach(k => result[k] = _.pluck(target, k))
// lodash 4.17.4ではpluckが廃止されているので↓を使う
// keys.forEach(k => result[k] = _.compact(_.map(target, k)))
return result
}
// ES6
const tallyTarget2 = target => {
const _keys = target.map(a => Object.keys(a)).reduce((a, b) => a.concat(b))
const keys = Array.from(new Set(_keys))
const result = {}
keys.forEach(k => {
result[k] = target.map(t => t[k]).filter(t => !!t)
})
return result
}
// for Legacy browser
const tallyTarget3 = function (target) {
debugger
var _keys = target.map(function (a) {
return Object.keys(a);
}).reduce(function (a, b) {
return a.concat(b);
});
var keys = _keys.filter(function (a, i, self) {
return self.indexOf(a) === i;
});
var result = {};
keys.forEach(function (k) {
result[k] = target.map(function (t) {
return t[k];
}).filter(function (t) {
return !!t;
});
});
return result;
};
document.getElementById('lodash').innerText = JSON.stringify(tallyTarget1(target), null, ' ')
document.getElementById('es6').innerText = JSON.stringify(tallyTarget2(target), null, ' ')
document.getElementById('es5').innerText = JSON.stringify(tallyTarget3(target), null, ' ')